Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python

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 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!') ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata