Python, like C + +, supports multiple inheritance. Although the concept is easy, the hard work is that if a subclass invokes a property that itself does not have a definition, it is in what order to find it in the parent class, especially if many of the parent classes contain the same name attribute.
For classic and modern classes, the order in which attributes are found is different. Now let's look at two different manifestations of the classic and new classes:
Classic class:
The code is as follows:
#! /usr/bin/python
#-*-Coding:utf-8-*-
Class P1 ():
def foo (self):
print ' P1-foo '
Class P2 ():
def foo (self):
print ' P2-foo '
def bar (self):
print ' P2-bar '
Class C1 (P1,P2):
Pass
Class C2 (P1,P2):
def bar (self):
print ' C2-bar '
Class D (C1,C2):
Pass
if __name__ = = ' __main__ ':
D=d ()
D.foo ()
D.bar ()
Results of execution:
The code is as follows:
P1-foo
P2-bar
The code example, drawing a diagram, easy to understand:
Judging from the output of the classic class above,
When instance D calls Foo (), the search order is d = = C1 = P1,
When instance D calls bar (), the search order is d = C1 = P1 = P2
Summary: The Classic class Search method is based on "left to right, depth first" way to find properties. D First look for whether it has the Foo method, no find the nearest parent class C1 the method, if not, continue to look up until the method is found in P1, find the end.
New class:
The code is as follows:
#! /usr/bin/python
#-*-Coding:utf-8-*-
Class P1 (object):
def foo (self):
print ' P1-foo '
Class P2 (object):
def foo (self):
print ' P2-foo '
def bar (self):
print ' P2-bar '
Class C1 (P1,P2):
Pass
Class C2 (P1,P2):
def bar (self):
print ' C2-bar '
Class D (C1,C2):
Pass
if __name__ = = ' __main__ ':
Print d.__mro__ #只有新式类有__mro__属性, tell me what the search order is.
D=d ()
D.foo ()
D.bar ()
Results of execution:
The code is as follows:
( , , , , , )
P1-foo
C2-bar
Judging from the output of the above-mentioned new class,
When instance D calls Foo (), the search order is d = C1 = C2 = P1
When instance D calls bar (), the search order is d = = C1 = C2
Summary: The search for the new class is based on the "breadth first" approach to finding attributes.