Sub topic 1
Review: Instance Methods and self
Instance methods are the default kind of method in Python. @classmethod and @staticmethod are defined by how they differ from them. This chapter sets out the working model of instance methods and self that the rest of the tutorial relies on. It also covers the errors that confuse people most often.
Prerequisites
This chapter assumes you can already do the following:
- Define a class with
classand create objects by calling it. - Write a function with positional and default parameters.
- Read
@namedecorator syntax above a function, even if you have never written a decorator. - Tell an attribute stored on an object from a variable local to a function.
You do not need to know how descriptors work. That comes in a later chapter.
What an instance method is
An instance method is a function defined inside a class body whose first parameter receives the object the method was called on. 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):
self.balance += amount
return self.balance
def describe(self):
return f"{self.owner}: {self.balance}"
acct = Account("Ada", 100)
print(acct.deposit(50)) # 150
print(acct.describe()) # Ada: 150Account defines three methods: __init__, deposit, and describe. Each lists self first, but the calls above never pass it. acct.deposit(50) supplies one argument, while the function deposit takes two parameters. Python fills the gap, and the next section explains how.
How self gets filled in
When you write acct.deposit(50), Python performs two steps.
- It looks up the name
depositonacct. It finds a plain function stored in the classAccount. Because the function was found through an instance, Python wraps it in a bound method object that remembersacct. - It calls the bound method with
(50). The bound method calls the original function withacctinserted as the first argument, so the function runs asdeposit(acct, 50).
You can see the result by calling the function through the class and passing the instance yourself:
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def describe(self):
return f"{self.owner}: {self.balance}"
acct = Account("Ada", 100)
print(acct.describe()) # Ada: 100
print(Account.describe(acct)) # Ada: 100The two calls are equivalent. The first form is the one you write in practice. The second shows that self is an ordinary parameter. Nothing special happens inside the function body. The only special thing is the automatic insertion of the instance when the lookup goes through an object.
Bound methods are objects
The bound method from step 1 is a real object. You can store it in a variable, pass it to another function, or inspect it.
class Account:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
return self.balance
acct = Account(100)
add = acct.deposit # no call yet
print(add.__self__ is acct) # True
print(add.__func__ is Account.deposit) # True
add(10)
print(acct.balance) # 110__self__ is the instance the method is bound to. __func__ is the underlying function stored on the class. This is why you can pass acct.deposit as a callback and it still updates the right account later. Storing the bound method keeps a reference to the instance.
self is a convention
self is not a keyword. Python only cares about position, so the first parameter receives the instance whatever it is called.
class Odd:
def show(this):
return type(this).__name__
print(Odd().show()) # OddThis works, but do not do it. Every Python style guide, linter, and reader expects self. Using another name makes the code harder to read and gains nothing.
Instance state lives in self
Attributes assigned through self belong to that one instance. Each object gets its own storage, so two instances of the same class do not share values.
class Counter:
def __init__(self):
self.count = 0
def bump(self):
self.count += 1
return self.count
a = Counter()
b = Counter()
a.bump()
a.bump()
b.bump()
print(a.count, b.count) # 2 1Each call to bump receives a different self, so each one updates a different count. The method code exists once on the class. The data exists once per instance. That split is the core of the instance method model.
An instance method can also read class attributes through self, because attribute lookup falls back from the instance to its class. The next chapter covers that distinction. Here, remember that self.x means "look for x on this instance, then on its class".
Methods calling methods
Inside a method, you call another method on the same object through self. A bare name does not work.
class Report:
def __init__(self, title, lines):
self.title = title
self.lines = lines
def header(self):
return self.title.upper()
def render(self):
body = "\n".join(self.lines)
return f"{self.header()}\n{body}"
r = Report("Sales", ["north: 10", "south: 7"])
print(r.render())The output is:
SALES
north: 10
south: 7self.header() goes through the same lookup as any other method call. If a subclass overrides header, render will use the subclass version, because self is an instance of the subclass. This is the behavior that later makes cls in class methods useful.
Returning self for chaining
A method that changes state usually returns None. Some designs return self so that calls can be chained.
class QueryBuilder:
def __init__(self, table):
self.table = table
self.conditions = []
self.row_limit = None
def where(self, condition):
self.conditions.append(condition)
return self
def limit(self, n):
self.row_limit = n
return self
def build(self):
sql = f"SELECT * FROM {self.table}"
if self.conditions:
sql += " WHERE " + " AND ".join(self.conditions)
if self.row_limit is not None:
sql += f" LIMIT {self.row_limit}"
return sql
query = QueryBuilder("users").where("age > 18").where("active = 1").limit(10)
print(query.build())
# SELECT * FROM users WHERE age > 18 AND active = 1 LIMIT 10Each method mutates the same object and hands it back, so the next call has something to work on. Use this style deliberately. It is clear in builders, but surprising if the same class also has methods that return new objects.
Methods are looked up at call time
A method is just a function stored in the class namespace. Because lookup happens when you call it, you can add one to an existing class and every instance sees it:
class Account:
def __init__(self, balance):
self.balance = balance
def double(self):
self.balance *= 2
return self.balance
Account.double = double
acct = Account(50)
print(acct.double()) # 100Binding only happens for functions found on the class. A function stored in an instance's own attributes is not bound, so self is not inserted:
class Account:
def __init__(self, balance):
self.balance = balance
acct = Account(50)
acct.show = lambda self: self.balance
try:
acct.show()
except TypeError as error:
print(error)The call fails with a message saying show() is missing one required positional argument, 'self'. The lambda sits in the instance, so lookup returns it unchanged. To call it you would have to write acct.show(acct). Binding is a property of the class lookup path, not of functions in general. The binding chapter later in this tutorial explains the mechanism behind this.
Common errors
Most mistakes with instance methods fall into a few patterns. Each one produces a recognizable error.
Forgetting self in the definition
class Greeter:
def hello():
return "hi"
g = Greeter()
g.hello()This raises a TypeError along the lines of Greeter.hello() takes 0 positional arguments but 1 was given. The message counts the instance that Python inserted, even though you wrote no arguments in the call. The fix is to add self to the parameter list. If the method really needs no instance, that is a signal to consider a static method, which a later chapter covers.
Calling an instance method on the class without an instance
class Account:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
Account.deposit(50)This raises TypeError: Account.deposit() missing 1 required positional argument: 'amount'. Python took 50 as self, leaving amount empty. The error message names amount, not self, which tends to mislead. When an argument seems to be missing and you called through a class, check whether you meant to call through an instance.
Forgetting the self. prefix
class Counter:
def __init__(self):
self.count = 0
def bump(self):
count += 1Calling bump() raises UnboundLocalError. Inside the method, count += 1 creates a local variable named count, which has no value yet. The attribute self.count is a different thing. Always reach instance data through self.
The reverse mistake is silent. Assigning count = 1 in a method works without error, but sets a local variable that disappears when the method returns, and the instance is unchanged.
Misspelled attribute names
Python lets you create attributes at any time, so a typo does not raise an error when you assign:
class Account:
def __init__(self, balance):
self.balance = balance
def reset(self):
self.balence = 0 # typo: creates a new attribute
acct = Account(80)
acct.reset()
print(acct.balance) # 80The reset has no effect on balance, and nothing complains. Tests, linters, and type checkers catch this. Defining __slots__ also prevents it, at the cost of flexibility.
Mutable default arguments
Default values are evaluated once, when the function is defined, not on each call. A list default is therefore shared across every call that omits it.
class Basket:
def __init__(self, items=[]): # shared list: a bug
self.items = items
def add(self, item):
self.items.append(item)
a = Basket()
b = Basket()
a.add("apple")
print(b.items) # ['apple']Both baskets hold the same list object. The standard fix uses None as the default and builds a fresh list inside the method:
class Basket:
def __init__(self, items=None):
self.items = [] if items is None else list(items)
def add(self, item):
self.items.append(item)
a = Basket()
b = Basket()
a.add("apple")
print(b.items) # []The extra list(items) copies a list passed in by the caller, so the basket does not alias the caller's data.
Quick reference
The table summarizes what you can rely on for instance methods in the chapters that follow.
| Question | Answer for an instance method |
|---|---|
| What is the first parameter? | The instance the method was called on, named `self` by convention |
| Who passes it? | Python, when the method is looked up through an instance |
| What does `Class.method(obj, ...)` do? | Calls the same function with `obj` as `self`, with no binding step |
| Where does the function live? | In the class namespace, once for all instances |
| Where does per-object data live? | On the instance, through `self.name = value` |
| Can it reach class-level data? | Yes, through `self.name` lookup or `type(self).name` |
Why this matters for the next chapters
Instance methods tie behavior to one specific object. Every method in this chapter needs a particular Account, Counter, or Report to do its work, because it reads or writes self.
Some behavior does not belong to one object. A function that builds a new instance from a string has no instance yet to pass in. A helper that checks whether a number is a valid temperature does not use any instance data at all. Python offers two more kinds of methods for these cases. They differ from instance methods only in what Python passes as the first argument, and that comes down to the lookup and binding step you saw above.
Exercises
Exercise
A class defines def total(self, tax): return self.price * (1 + tax). You have item = Item(10) and call Item.total(0.2). What error do you get, and which two calls would work instead?
Show answer
Python treats 0.2 as self, so the required argument tax is missing and you get a TypeError saying total() is missing 1 required positional argument: 'tax'. Either item.total(0.2) or Item.total(item, 0.2) works, and both return 12.0.
Exercise
What does this code print, and why? class Tally: def _init_(self): self.n = 0 def add(self): n = self.n + 1 t = Tally() t.add() t.add() print(t.n)
Show answer
It prints 0. Inside add, n = self.n + 1 assigns a local variable named n, which disappears when the method returns. The attribute self.n is never changed. The fix is self.n = self.n + 1 or self.n += 1.
Exercise
You store cb = acct.deposit and later call cb(25) after reassigning the name acct to a different Account object. Which account receives the deposit, and which attributes of cb show this?
Show answer
The original account receives the deposit. The bound method keeps a reference to the instance it was created from, so reassigning the name acct does not change it. cb.__self__ is the original instance and cb.__func__ is the plain function Account.deposit.