Full answer
python
class Account:
bank = "Schoolabe Bank"
count = 0
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
Account.count += 1
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
return self.balance
a, b = Account("Asha"), Account("Ben", 100)
print(a.deposit(50), b.balance, Account.count, a.bank)
b.bank = "Other"
print(a.bank, b.bank, Account.bank)
print(Account.deposit(a, 10))Output:
text
50 100 2 Schoolabe Bank
Schoolabe Bank Other Schoolabe Bank
60Each account keeps its own owner and balance, while count lives on the class and tracks how many accounts exist. Assigning b.bank creates an instance attribute that hides the class attribute for b only; a and the class still see the original. The last line shows what a.deposit(10) really does: it calls the function on the class with a as self. Mutable class attributes, such as a shared list, are a common source of bugs because every instance modifies the same object.
python
class Account:
bank = "Schoolabe Bank"
count = 0
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
Account.count += 1
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
return self.balance
a, b = Account("Asha"), Account("Ben", 100)
print(a.deposit(50), b.balance, Account.count, a.bank)
b.bank = "Other"
print(a.bank, b.bank, Account.bank)
print(Account.deposit(a, 10))Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Instance attributes live on self
- Class attributes are shared
- Assigning on an instance shadows the class attribute
- Methods get self automatically
- Avoid mutable class attributes
Common mistakes
- Putting a list as a class attribute for per-instance data
- Forgetting self in method signatures
Follow-ups
- What are classmethod and staticmethod for?
- When would you use a dataclass instead?
Tips
- Show shadowing of a class attribute