Data Structures and Algorithms with Object-Oriented Design Patterns in Python
next up previous index

Multiple Inheritance

In Python a class can be derived from one or more base classes. For example, consider the following class definitions:

class A(object):
    def f(): pass
class B(object): pass
    def f(): pass
class C(A, B): pass
The class C extends both classes A and B. Therefore, the C class inherits class attributes from both base classes.

An interesting question arises when more than one base class defines an attribute with the same name. For example, A and B both define a method named f. Given an instance c of class C, what method does the expression c.f() call?

The method called is determined by a set of rules called the Python method resolution order . In order to handle the general case, the rules are quite complex and are beyond the scope of this book. (For a thorough explanation, see [44]). However, a simple cases such as this, the rules are straightfoward: To find a name, first search the namespace of class C, and then search base classes in the order given. That is, search A first and then search B. Therefore, in this case the function invoked by the expression c.f() is the function A.f.


next up previous index

Bruno Copyright © 2003, 2004 by Bruno R. Preiss, P.Eng. All rights reserved.