Linux/Unix > Python Essential Reference, Second Edition > 7. Classes and Object-Oriented Programming > Inheritance | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105086039028125016133222

### Inheritance

Inheritance is a mechanism for creating a new class that specializes or modifies the behavior of an existing class. The original class is called a base class or a superclass. The new class is called a derived class or a subclass. When a class is created via inheritance, it “inherits” the attributes defined by its base classes. However, a derived class may redefine any of these attributes and add new attributes of its own.

Inheritance is specified with a comma-separated list of base-class names in the `class` statement. For example:

    class A:
        varA = 42
        def method1(self):
            print "Class A : method1"

    class B:
        varB = 37
        def method1(self):
            print "Class B : method1"
        def method2(self):
            print "Class B : method2"
    class C(A,B):      # Inherits from A and B
        varC = 3.3
        def method3(self):
            print "Class C : method3"

    class D: pass
    class E(C,D): pass

When searching for an attribute defined in a base class, the base classes are searched using a depth-first search algorithm in the same order as specified in the class definition. For example, in class E in the preceding example, base classes are searched in the order C,A, B, D. In the event that multiple base classes define the same symbol, the first symbol encountered in the search process is used. For example:

    c = C()            # Create a 'C'
    c.method3()        # Invoke C.method3(c)
    c.method1()        # Invoke A.method1(c)
    c.varB             # Access B.varB

If a derived class defines an attribute with the same name as an attribute in a base class, instances of the derived class use the attributes in the derived class. If it’s ever necessary to access the original attribute, a fully qualified name can be used as follows:

    class D(A):
       def method1(self):
           print "Class D : method1"
           A.method1(self)            # Invoke base class method

One notable use of this is in the initialization of class instances. When an instance is created, the `_ _init_ _()` methods of base classes are not invoked. Thus, it’s up to a derived class to perform the proper initialization of its base classes, if necessary. For example:

    class D(A):
        def _ _init_ _(self, args1):
            # Initialize the base class
            A._ _init_ _(self)
            # Initialize myself
            ...

Similar steps may also be necessary when defining cleanup actions in the `_ _del_ _()` method.

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.