Remember what the python method resolution order (MRO) mechanism

Has been using python are holding a cookbook and a direct line and a document library, the details will rarely flies so completely, turn the document will encounter problems.

See this example today, when I suddenly touched my blind spot, I'm not sure this inheritance hierarchy call super.foo () which will first bind. Because the class hierarchy before I wrote this library will not, so do not go elegant.

Since encounter problems, it is necessary to understand, to solve this problem. Read the official document , python in the case of multiple inheritance, the parent class will first inherited link all put a list inside, and then merge, and then when the function is bound, left after the first encounter when matched directly binding.

Po the following code.

 
 
class A:
def foo(self):
print("A")


class B(A):
def foo(self):
super(B, self).foo()
print("B")


class C(B, A):
def foo(self):
super(C, self).foo()
print("C")


class D(C):
def foo(self):
super(D, self).foo()
print("D")


class E(D, C):
pass


a = A()
b = B()
c = C()
d = D()
e = E()

a.foo()
print(" ")
b.foo()
print(" ")
c.foo()
print(" ")
d.foo()
print(" ")
e.foo()
 

answer:

According to the calculation method of the document

L(A) = O

L(B) = B  A O

L (C) = C merge (INCLUDING, AO, BA) = CBAO

L(D) = D C B A O

L (E) = E + merge (DCBAO, CBAO, DC) = EDCBAO

 

So super (type, self) .foo () method for instance is bound will be derived in accordance with the above solution.

 

Guess you like

Origin www.cnblogs.com/jason-koo/p/11504078.html