Methods that change an object
🌍 In real life. A tally counter at a cricket gate clicks up by one for each person who comes in. Each gate has its own counter: clicking at Gate A doesn't change Gate B. Objects work the same way:
- a method can change its object's attributes:
self.count = self.count + 1 - each object keeps its own values
- so calling a method on one object leaves the others alone
The idea in one sentence: a method can change its own object's attributes through self, so each object keeps its own state, and the methods are the safe way to change it.
Its words:
- state: the current values of an object's attributes, like a balance
- changing the object:
self.count = self.count + 1inside a method - guard: a check in a method that refuses a bad change by raising an error
Step by step, for gate_a.click():
- Python runs
clickwithself=gate_a. self.count = self.count + 1reads gate A's count and writes the new one back onto gate A.- Gate B's count isn't touched: it's a different object.
A bank account is the classic example. The balance should only change through deposit and withdraw. withdraw refuses (raises a ValueError, Chapter 18) when there isn't enough money, so the balance can never go wrong:
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance = self.balance + amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("not enough money")
self.balance = self.balance - amount
acc = Account("Ana", 50)
acc.deposit(20)
acc.withdraw(30)
print(acc.balance)
try:
acc.withdraw(500)
except ValueError as e:
print("Refused:", e)
print(acc.balance)Remember Chapter 13: a name points to an object. Two names can point to the same object, like two people holding keys to the same locker. A change made through one key shows up for the other. Here Account(…) is called only once, so there is only one account:
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance = self.balance + amount
mine = Account("Ana", 50)
also_mine = mine
also_mine.deposit(25)
print(mine.balance)
print(mine is also_mine)Mistakes and edge cases.
- Forgetting self. on the left.
balance = self.balance + ninsidedepositmakes a local variable and throws it away; the account's balance doesn't change, and there's no error. - Changing the attribute from outside.
acc.balance = -500skips the guard inwithdraw; use the methods. - Two names, one object.
b = athenb.deposit(5)changes the one account both names point to (above). - Returning instead of storing. A method that only
returns the new balance leaves the object unchanged unless it also setsself.balance.
Quiz
What does this print?
class Counter: def __init__(self): self.count = 0 def increment(self): self.count = self.count + 1 c = Counter() c.increment() c.increment() c.increment() print(c.count)What does this print?
class Counter: def __init__(self): self.count = 0 def increment(self): self.count = self.count + 1 a = Counter() b = Counter() a.increment() print(a.count, b.count)What does this print?
class Box: def __init__(self): self.items = [] def add(self, item): self.items.append(item) x = Box() y = x y.add("pen") print(x.items)Why can
withdrawraise a ValueError instead of returning a message?- So the caller can't miss the problem, and the balance never goes wrong
- Methods can't return strings
- raise is faster
Which line has a mistake?
class Counter: def __init__(self): self.count = 0 def increment(self): count = self.count + 1
Coding tasks
Write a class
Counterwhose objects start withcount0 and have a methodincrement()that adds 1.Write a class
Accountwith abalance, a methoddeposit(amount), and a methodwithdraw(amount)that raises aValueErrorif the amount is more than the balance.Write a class
Playlistwhose objects start with an empty listsongs, with a methodadd(song)that appends to it. Each playlist needs its own list.