Since you already know about functions, you already know
class methods. Methods are just
function objects created by def
statements nested
in a class
statement’s body. From an
abstract perspective, methods provide behavior for instance objects
to inherit. From a programming perspective, methods work in exactly
the same way as simple functions, with one crucial exception: their
first argument always receives the instance object that is the
implied subject of a method call. In other words, Python
automatically maps instance method calls to class method functions
like so:
instance.method(args...) => becomes => class.method(instance, args...)
where the class is determined by Python’s inheritance search
procedure. The special first argument in a class method is usually
called self
by convention; it’s similar to
C++’s this
pointer, but Python methods must
always explicitly qualify self
to fetch or change
attributes of the instance being processed by the current method
call.
Let’s turn to an example; suppose we define the following class:
class NextClass: # define class def printer(self, text): # define method print text
The name printer
references a function object;
because it’s assigned in the class
statement’s scope, it becomes a class attribute and is
inherited by every instance made from the class. The
printer
function may be called in one of two
ways—through an instance, or through the class itself:
>>>x = NextClass()
# make instance >>>x.printer('Hello world!')
# call its method Hello world!
When called by qualifying an instance like this,
printer
’s self
argument
is automatically assigned the instance object (x
),
and text
gets the string passed at the call
(”Hello world!"
). Inside
printer
, self
can access or set
per-instance data, since it refers to the instance currently being
processed. We can also call printer
by going
through the class, provided we pass an instance to the
self
argument explicitly:
>>> NextClass.printer(x, 'Hello world!')
# class method
Hello world!
Calls routed through the instance and class have the exact same effect, provided we pass the same instance object in the class form. In a moment, we’ll see that calls through a class are the basis of extending (instead of replacing) inherited behavior.