Python and the order of methods in multiple inheritance

In Python, if you define two classes with the same method and intend these two classes to be parent classes, like:

class A(object):
     def hello(self):
         print "hello from class a" 

and

class B(object):
     def hello(self):
         print "hello from class b"

when you define a child class and add two parent classes in order A and B:

class C(A, B):
     def __init__(self):
         self.hello()

The method that is used when calling self.method () is the one that belongs to A, or the first class in the inheritance list:

>>> C()
hello from class a
<__main__.C object at 0x10571e9d0>

, , . - , , , ( super().__ init __() ..) , ?

,

+3
2

, , ( C3).

, mro, python ( 2.3+). AFAIK C3-.


C3- . , C(B1, ..., Bn) mro Bi , .

, , :

>>> class A(object): pass
>>> class B(object): pass
>>> class C(object): pass
>>> class D(object): pass
>>> class E(object): pass
>>> class K1(A,B,C): pass
>>> class K2(D,B,E): pass
>>> class K3(D,A):   pass
>>> class Z(K1,K2,K3): pass

mro python2.2 ( ), :

L[A] = A O
L[B] = B O
L[C] = C O
L[D] = D O
L[E] = E O
L[K1]= K1 A B C O
L[K2]= K2 D B E O
L[K3]= K3 D A O
L[Z] = Z K1 K3 A K2 D B C E O
# in current versions of python (2.3+):
# L[Z] = Z K1 K2 K3 D A B C E O

, Z A D, K3 D. , . X Y , Y .

, C(B1, ..., Bn). B1, ..., Bn C. Bi Bi. , C, , C B1.

, , python , :

>>> class A(object):pass
... 
>>> class B(object, A): pass
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Cannot create a consistent method resolution
order (MRO) for bases object, A

, , :

>>> class B(A, object): pass
... 
>>> B.mro()
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]

(, object), , C(B1, ..., Bn) B1 ( object), B2 .., Bn:

>>> class A(object): pass
... 
>>> class B(object): pass
... 
>>> class A1(A): pass
... 
>>> class A2(A1): pass
... 
>>> class B1(B): pass
... 
>>> class C(object): pass
... 
>>> class C1(C): pass
... 
>>> class C2(C1):pass
... 
>>> class C3(C2): pass
... 
>>> class D(A2, B1, C3): pass
... 
>>> D.mro()
[<class '__main__.D'>, <class '__main__.A2'>, <class '__main__.A1'>, <class '__main__.A'>, <class '__main__.B1'>, <class '__main__.B'>, <class '__main__.C3'>, <class '__main__.C2'>, <class '__main__.C1'>, <class '__main__.C'>, <class 'object'>]

, Bi, python , , , .

+3

: http://www.python.org/download/releases/2.3/mro/

Python () .

, . __mro__ mro().

class A(object):
    def hello(self):
        print 'hello from A'

class B(object):
    def hello(self):
        print 'hello from B'

class C(A, B):
    def __init__(self):
        self.hello()

>>> C()
hello from A
>>> print C.__mro__
(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>)
>>> print C.mro()
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>]
0

All Articles