Methods
Functions inside a class are methods. They act on the object's own data through self:
class Counter: def __init__(self): self.value = 0 def bump(self, by=1): self.value += by
c = Counter()
c.bump() # c.value is now 1A method can also receive another object and update its attributes, e.g. other.balance += amount. other is self asks whether both names refer to the same object, rather than whether their values are equal.
See it run
class Counter: def __init__(self): self.n = 0 def bump(self, by): self.n = self.n + by return self.n c = Counter() c.bump(2) c.bump(3) print(c.n)
Watch self in each method frame: it is the same object as c.
Practice methods
Exercise 1
Build BankAccount(owner, balance=0) with:
deposit(amount): adds to the balancewithdraw(amount): subtracts and returnsTrue, but if there isn't enough money it leaves the balance alone and returnsFalse
Exercise 2
Build WaterTank(capacity) starting at level = 0. fill(amount) adds up to capacity and returns the amount actually added. use(amount) subtracts and returns True if enough exists, otherwise returns False without changing level. Inputs are nonnegative; exact depletion is allowed.
Exercise 3
Build Wallet(balance=0) with transfer(other, amount). Positive amounts up to the sender's balance move to the other wallet and return True. Self transfers and zero, negative, or excessive amounts return False and change neither wallet.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.