Show how self refers to the instance in a Python method.
self is simply the name that a method uses for the object it was called on. It is the first parameter of the method, and the interpreter passes the instance in automatically.
class Counter:
def __init__(self):
self.count = 0
def increment(self, by=1):
self.count += by
return self.count
def who(self):
return self
c = Counter()
print(c.increment())
print(c.increment(5))
print(c.who() is c)
The increment method reads and writes self.count, so each call works on the object it was called through. The who method returns self itself, and the identity check confirms that it is the very same object and not a copy of it.
The last line is worth pausing on, because the statement c.increment() is really just a short way of writing Counter.increment(c). Python looks up increment on the class and then calls it with the instance as the first argument. The dot notation is a convenience, and self is what makes that convenience work.
Because self is an ordinary parameter, it can be anything that the method is called with. That is what makes it possible to call a method in an unbound way, and it is also what makes the calling convention visible rather than hidden, because you can always see which object a method operates on by reading its first line.