Python Methods and self: Reading and Changing Object State
A method is a function defined inside a class. Python passes in the object you call it on as the first parameter, named self.
Read Classes and objects first.
Define a method that reads state
class Counter:
def __init__(self):
self.count = 0
def show(self):
print(f"Count: {self.count}")
clicks = Counter()
clicks.show()
clicks.show() runs show with self set to clicks. The method reads
self.count from that object. An object's attributes are its state.
Change state in a method
A method can change attributes on self. The change stays on the object
after the method ends.
class Counter:
def __init__(self):
self.count = 0
def add(self, amount):
self.count += amount
clicks = Counter()
clicks.add(2)
clicks.add(5)
print(clicks.count)
You pass only amount. Python fills in self for you, so the result is 7.
What self really is
a.add(3) is shorthand for Counter.add(a, 3). The object before the dot
becomes self.
class Counter:
def __init__(self):
self.count = 0
def add(self, amount):
self.count += amount
a = Counter()
b = Counter()
a.add(3)
Counter.add(b, 10)
print(a.count, b.count)
Both calls work the same way. Each one changes only its own object.
Return a value and call other methods
A method can return a result, like any function. It calls another method
on the same object with self..
class Wallet:
def __init__(self, money):
self.money = money
def can_afford(self, price):
return price <= self.money
def buy(self, price):
if self.can_afford(price):
self.money -= price
return True
return False
wallet = Wallet(20)
print(wallet.buy(15))
print(wallet.buy(15))
print(wallet.money)
The first purchase fits, so money drops to 5. The second does not fit,
so buy returns False and leaves money alone.
Note: Every method needs self as its first parameter. Leave it out and
calling the method raises TypeError: Counter.show() takes 0 positional arguments but 1 was given.
See also: Parameters and return, Method overriding and super().
Your turn
Finish toggle so it flips self.on between True and False.
class Lamp:
def __init__(self):
self.on = False
def toggle(self):
# add one line: set self.on to the opposite of its current value
pass
lamp = Lamp()
lamp.toggle()
print(lamp.on)
lamp.toggle()
print(lamp.on)
Expected output
True
False