Python, like C + +, supports multiple inheritance. The concept is easy, but the hard work is that if subclasses call an attribute that is not defined by itself, it is in what order it goes to the parent class, especially if many of the parent classes contain the same attribute.
For both classical and new classes, the search order for attributes is different. Now let's look at two different manifestations of classic and new classes:
Classic class:
Copy Code code 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:
Copy Code code as follows:
Draw a diagram of the code instance to facilitate understanding:
In terms of the output from 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 =>
Summary: The classic class search is based on the "left to right, depth first" way to find attributes. D Find out if it has the Foo method first, not the nearest parent class C1, and if not, continue to look up until you find the method in P1 and find the end.
New class:
Copy Code code 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__属性 to tell what order to find
D=d ()
D.foo ()
D.bar ()
Results of execution:
Copy Code code as follows:
(<class ' __main__.) D ', <class ' __main__. C1 ', <class ' __main__. C2 ', <class ' __main__. P1 ', <class ' __main__. P2 ', <type ' object ' >)
P1-foo
C2-bar
Judging from the output of the new class above,
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 new type of search method is to use the "breadth first" way to find attributes.