Sub topic 4
Defining behavior with instance methods
This chapter assumes you can write Python functions and that you have seen a class with an __init__ method that stores attributes on self. Here you will focus on the methods that act on that stored state.
What an instance method is
An instance method is a function defined inside a class body. Python passes the instance it was called on as the first argument. By convention that parameter is named self.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
return self.balance
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
return self.balance
def summary(self):
return f"{self.owner}: {self.balance}"
acct = Account("Ana", 100)
print(acct.deposit(50)) # 150
print(acct.summary()) # Ana: 150deposit and withdraw change the object's state. summary only reads it. Both kinds are ordinary instance methods. The difference is a design choice, not something Python enforces.
How the call is translated
When you write acct.deposit(50), Python looks up deposit on the class and binds the instance to it. The call is equivalent to Account.deposit(acct, 50).
You can see this directly:
acct = Account("Ana", 100)
acct.deposit(50) # balance is 150
print(Account.deposit(acct, 25)) # 175, same function called explicitly
method = acct.deposit # a bound method: acct is already attached
method(10)
print(acct.balance) # 185
print(method.__self__ is acct) # TrueA bound method is an object that remembers its instance. You can store it, pass it to other functions, or use it as a callback, and it will still update the right object.
Methods that call other methods
Inside a method, call a sibling method through self. A bare name such as deposit(10) refers to a global or local variable, not to the method.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
return self
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
return self
def transfer_to(self, other, amount):
self.withdraw(amount) # reuses the validation in withdraw
other.deposit(amount)
return self
a = Account("Ana", 100)
b = Account("Ben")
a.transfer_to(b, 40).deposit(5) # chaining works because methods return self
print(a.balance, b.balance) # 65 40Returning self allows chaining, as in the last call. Use it where it reads well. Otherwise, returning None signals that the method is called for its effect.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: ... takes 1 positional argument but 2 were given` | The method was defined without `self`, so the bound instance consumed the only parameter. | Add `self` as the first parameter. |
| `NameError: name 'balance' is not defined` | The method used `balance` instead of `self.balance`. | Read and write state through `self`. |
| `AttributeError` on a method name | A typo, or the method was defined at the wrong indentation level, outside the class. | Check the spelling and indentation. |
| The method seems to do nothing | You wrote `acct.summary` without parentheses, which only evaluates to the bound method. | Call it with `acct.summary()`. |
| A method returns `None` unexpectedly | The method has no `return` statement. | Return the value you intend to use. |
Exercise
Exercise
Add a method apply_interest(self, rate) to Account that increases the balance by balance * rate and returns the new balance. What does Account("Ana", 200).apply_interest(0.05) return, and which call is equivalent to acct.apply_interest(0.05) when called through the class?
Show answer
One implementation is def apply_interest(self, rate): self.balance += self.balance * rate; return self.balance. The call Account("Ana", 200).apply_interest(0.05) returns 210.0. The equivalent call through the class is Account.apply_interest(acct, 0.05).