6.4 Using Class Methods

6.4 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.

6.4.1 Example

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 waysthrough 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.



Learning Python
Learning Python: Powerful Object-Oriented Programming
ISBN: 0596158068
EAN: 2147483647
Year: 1999
Pages: 156
Authors: Mark Lutz

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net