Sub topic 1
Review: Instance Methods and self
This chapter reviews how ordinary methods work in Python. Class methods and static methods are defined in contrast to them, so you need a precise picture of what an instance method receives and how.
Prerequisites
This chapter assumes you can already do the following:
- Define a class with
__init__and store values as instance attributes. - Read the
@namedecorator syntax above a function, even if you have never written a decorator. - Tell a class attribute from an instance attribute. The next chapter reviews this.
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. The name is not a keyword. Python passes the object in automatically, and you choose the name.
class Counter:
def __init__(self, start=0):
self.value = start
def increment(self):
self.value += 1
return self.value
c = Counter()
print(c.increment()) # 1
print(c.increment()) # 2The call c.increment() supplies no arguments, yet increment declares one parameter. Python fills self with c. This is why the method can read and change c.value.
What self refers to
self is the specific instance the call was made on. Two instances of the same class have separate data, so the same method gives different results depending on which instance calls it.
a = Counter(10)
b = Counter(100)
a.increment()
print(a.value) # 11
print(b.value) # 100Each call receives a different self. The method code is shared, and the data is not.
The two ways to call an instance method
Calling a method through an instance is shorthand. You can also call it through the class and pass the instance yourself.
c = Counter()
print(c.increment()) # 1 (bound call)
print(Counter.increment(c)) # 2 (explicit call)Both lines run the same function. In the first, Python supplies c for you. In the second, you supply it. Seeing both forms makes it clear that self is an ordinary first argument.
The table below summarizes the two call styles.
| Call style | Example | Who supplies `self` |
|---|---|---|
| Through the instance | `c.increment()` | Python |
| Through the class | `Counter.increment(c)` | You |
How the call flows
The diagram shows what happens when you write c.increment().
The lookup happens on the class, not on the instance. The instance only supplies the object to bind. A later chapter explains this binding step in detail.
Instance methods need an instance
An instance method is meant to work on the data of one object. If a method never uses self, it still receives it, which is a hint that it may be in the wrong place.
class Greeter:
def hello(self, name):
return f"Hello, {name}!"
print(Greeter().hello("Ada")) # Hello, Ada!hello ignores self. It works, but you must create a Greeter object just to call it. Class methods and static methods address this kind of situation, as later chapters show.
Common errors
Two mistakes appear often with instance methods.
- Leaving out
selfin the definition. Python still passes the instance, so the call fails with aTypeErrorabout too many arguments. - Forgetting
self.when reading an attribute inside the method. The bare name is looked up as a local or global variable and raises aNameError.
class Broken:
def __init__(self):
self.count = 0
def show(self):
return count # NameError: should be self.count
class AlsoBroken:
def show():
return "hi"
try:
AlsoBroken().show()
except TypeError as error:
print(error)The second class prints a message saying show() takes 0 positional arguments but 1 was given. Python passed the instance, and the definition had no parameter to hold it.
What to carry forward
- An instance method receives the calling object as its first argument, named
selfby convention. c.method(x)is equivalent toClass.method(c, x).- The method body is shared by all instances. The data comes through
self. - A method that never touches
selfis a candidate for a different kind of method.
Exercise
Given class Box: with a method def size(self): return self.n, and b = Box() with b.n = 5, write the call that uses the class instead of the instance to get the same result as b.size().
Show answer
Box.size(b). Python passes b as self, so the method returns b.n, which is 5.
Exercise
A method is defined as def total(items): return sum(items) inside a class and called as obj.total([1, 2]). What happens, and why?
Show answer
It raises a TypeError because Python passes obj as the first argument, so the call supplies two arguments to a function that accepts one. The definition needs a self parameter, or the method should be a static method.