Sub topic 4
Defining behavior with instance methods
This chapter assumes you can write Python functions with arguments and return values, and that you have already written a class with an __init__ method. Here you will see what an instance method is, what Python does when you call one, and which mistakes come up most often.
What an instance method is
An instance method is a function defined inside a class body whose first parameter receives the object the method is called on. By convention that parameter is named self. The name is not a keyword, but every tool and reader expects it.
Attributes hold an object's state. Methods are the operations that read or change that state. A good method keeps the object consistent. For example, a bank account should never end up with a negative balance, and its methods are the place to enforce that.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
self._history = []
def deposit(self, amount):
self._check_amount(amount)
self.balance += amount
self._history.append(("deposit", amount))
def withdraw(self, amount):
self._check_amount(amount)
if amount > self.balance:
raise ValueError("insufficient funds")
self.balance -= amount
self._history.append(("withdraw", amount))
def statement(self):
return list(self._history)
def _check_amount(self, amount):
if amount <= 0:
raise ValueError("amount must be positive")
acct = Account("Ana", 100)
acct.deposit(50)
acct.withdraw(30)
print(acct.balance) # 120
print(acct.statement()) # [('deposit', 50), ('withdraw', 30)]Some details in this class are worth noting:
- Every method reads or writes attributes through
self. A bare name such asbalanceinside a method would be a local variable or a global, not the attribute. depositandwithdrawcall a helper,self._check_amount(...). Methods call other methods throughself, exactly as outside code calls them through the object.- The leading underscore in
_check_amountand_historyis a convention. It tells readers "internal, don't rely on this". Python does not enforce it. statementreturns a copy of the list. Returningself._historydirectly would let callers modify the account's history by accident.
What happens when you call a method
When you write acct.deposit(50), Python does not call deposit with only 50. It looks up deposit, finds a function in the class, and builds a bound method, which is a small object that pairs the function with the instance. Calling it passes the instance as the first argument.
acct = Account("Ana", 100)
acct.deposit(50) # the normal form
Account.deposit(acct, 25) # the same call, with self passed by hand
m = acct.deposit # a bound method; nothing has run yet
m(10)
print(acct.balance) # 185
print(type(Account.deposit)) # <class 'function'>
print(type(acct.deposit)) # <class 'method'>
print(m.__self__ is acct) # True
print(m.__func__ is Account.deposit) # TrueThis is why self appears in the definition but not in the call. The lookup follows these steps:
Functions bind because they implement __get__, the hook that attribute lookup uses to turn a class-level function into a bound method. You rarely write __get__ yourself, but it explains two behaviors: a function stored on an instance is not bound, and a function stored on the class is.
| Call form | What Python passes as `self` |
|---|---|
| `acct.deposit(50)` | `acct`, supplied automatically |
| `Account.deposit(acct, 50)` | `acct`, supplied by you |
| `m = acct.deposit; m(50)` | `acct`, stored inside `m` |
| `Account.deposit(50)` | nothing, so `50` becomes `self` and `amount` is missing |
The last row is an error. It raises a TypeError about a missing argument.
Methods that change state and methods that return values
Most methods fall into one of two groups: commands that change the object, and queries that report something about it. Python's built-in types follow a convention you should copy. A method that mutates in place returns None, as list.append and list.sort do. A method that produces a new value returns it, as sorted and str.upper do.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def move(self, dx, dy):
"""Mutate this point. Returns None."""
self.x += dx
self.y += dy
def moved(self, dx, dy):
"""Return a new point and leave this one alone."""
return Point(self.x + dx, self.y + dy)
def distance_to_origin(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
p = Point(3, 4)
q = p.moved(1, 1)
print(p.x, p.y) # 3 4
print(q.x, q.y) # 4 5
print(p.distance_to_origin()) # 5.0
p.move(10, 0)
print(p.x) # 13Returning None from a mutating method is a signal to the caller. It prevents the common bug p = p.move(1, 1), which would replace p with None.
Returning self for chaining
Sometimes a method returns self on purpose so that calls can be chained. This is common in builder objects that assemble a result step by step.
class MessageBuilder:
def __init__(self, greeting):
self.greeting = greeting
self.lines = []
self.signature = None
def add_line(self, text):
self.lines.append(text)
return self
def sign(self, name):
self.signature = name
return self
def build(self):
parts = [self.greeting, *self.lines]
if self.signature is not None:
parts.append(f"-- {self.signature}")
return "\n".join(parts)
text = (
MessageBuilder("Hello")
.add_line("Your order has shipped.")
.add_line("It should arrive Friday.")
.sign("Support")
.build()
)
print(text)The output is:
Hello
Your order has shipped.
It should arrive Friday.
-- SupportKeeping methods consistent with the object's invariants
An invariant is a fact about the object that must hold whenever outside code can see it, such as "the balance is never negative". Methods are the natural place to enforce invariants, because every change goes through them. Two habits help:
- Validate before you mutate. In
withdraw, the checks run beforeself.balancechanges, so a failed call leaves the object unchanged. - Do not leave an object half-updated if an exception can occur between two assignments. Compute the new values first, then assign them together.
class Range:
def __init__(self, low, high):
if low > high:
raise ValueError("low must not exceed high")
self.low = low
self.high = high
def resize(self, new_low, new_high):
if new_low > new_high: # check first
raise ValueError("low must not exceed high")
self.low, self.high = new_low, new_high # then assign both
r = Range(1, 5)
try:
r.resize(10, 2)
except ValueError as exc:
print("rejected:", exc)
print(r.low, r.high) # 1 5Because attributes are public, outside code can still write r.low = 100. If that matters, use a property to guard assignment, which a later chapter covers.
Common errors
Forgetting self in the definition. The call passes the instance, but the function has no parameter to take it.
class Counter:
def __init__(self):
self.count = 0
def increment(): # missing self
self.count += 1
try:
Counter().increment()
except TypeError as exc:
print(exc) # e.g. Counter.increment() takes 0 positional arguments but 1 was givenThe message is confusing because you passed no arguments. The count comes from the automatic self. The exact wording varies between Python versions.
Forgetting self. inside the body. Inside a method, count and self.count are different things.
class Tally:
def __init__(self):
self.count = 0
def double(self):
self.count = count * 2 # NameError: name 'count' is not definedCalling another method without self.. Writing _check_amount(amount) instead of self._check_amount(amount) also raises NameError. Methods are not visible as bare names inside other methods.
Shadowing a method with an attribute. The lookup in the diagram checks the instance dictionary first, so an attribute with the same name as a method hides it for that instance.
acct = Account("Ana", 100)
acct.deposit = 5 # legal, and it hides the method on this object
try:
acct.deposit(10)
except TypeError as exc:
print(exc) # 'int' object is not callableAvoid giving an attribute and a method the same name. A common case is a flag self.is_open and a method is_open().
Using a mutable default argument. Default values are evaluated once, when the function is defined, so a default list is shared across all calls.
class Log:
def __init__(self):
self.entries = []
def add(self, message, tags=[]): # one list shared by every call
tags.append("seen")
self.entries.append((message, tags))Use tags=None and create the list inside the method.
Treating a bound method as a snapshot. A bound method holds a reference to its instance, and acct.deposit reads the attributes the instance has when it is called, not when you took the reference. A stored callback such as button.on_click = acct.deposit also keeps acct alive for as long as the button exists.
When a method does not use self
Look again at _check_amount. It never touches self, so it could be a plain function or a staticmethod. Python allows this and does not warn. Leave such a method on the class when it is conceptually part of the class's work. The next chapter covers staticmethods and classmethods and when to prefer them.
Exercise
Given class Stack with __init__ setting self.items = [], write the methods push(self, item), pop(self), and peek(self). pop and peek must raise IndexError("stack is empty") on an empty stack, and peek must not change the stack. Then explain why s = Stack(); s.push(1); s.push(2) works but Stack.push(1) does not.
Show answer
Use def push(self, item): self.items.append(item), def peek(self): if not self.items: raise IndexError("stack is empty"); return self.items[-1], and def pop(self): if not self.items: raise IndexError("stack is empty"); return self.items.pop(). pop is a mutating method that also returns a value, like list.pop. s.push(1) binds s as self automatically. Stack.push(1) goes through the class, so no instance is bound: 1 is taken as self, and the required item argument is missing, which raises a TypeError. The explicit form Stack.push(s, 1) would work.
Exercise
A class has self.name = "x" set in __init__ and a method def name(self): .... What happens on obj.name(), and why?
Show answer
The instance dictionary is checked before the class, so obj.name finds the string "x". Calling it raises TypeError: 'str' object is not callable. The method in the class is hidden for that instance. Rename either the attribute or the method.