Using Class Methods
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.
Example
Let’s turn to an example; suppose we define the following class:
class NextClass: # define class
def printer(self, text): # define method
print textThe 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!') ...