Model related fields and operations in one small, purposeful class.
How It Works
Attributes store an object’s state; methods provide behavior. A good model reflects a real rule rather than simply naming a noun. For a bank balance, deposit() should validate positive amounts so code cannot accidentally create negative deposits.
For money in real applications, consider Decimal and additional domain rules, not only float arithmetic.
Step-by-Step Example
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self.balance += amount
account = Account("Ari", 20)
account.deposit(15)
print(account.owner, account.balance)
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
Ari 35
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Add a withdraw() method that refuses to withdraw more than the balance.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Allowing methods to accept invalid values that violate the intended model rules.
- Assuming that a public Python attribute cannot be changed from outside a class.
Key Takeaways
- Model related fields and operations in one small, purposeful class.
- Attributes store an object’s state; methods provide behavior.
- For money in real applications, consider Decimal and additional domain rules, not only float arithmetic.