This article mainly introduces Python's multiple inheritance understanding of the relevant data, multiple inheritance is not much easier to understand, here are examples to help you learn the reference, the need for friends can refer to the next
Python's understanding of multiple inheritance
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:
#! /usr/bin/python#-*-coding:utf-8-*-class P1 (): def foo (self): print ' P1-foo ' class P2 (): def foo (self): print ' P 2-foo ' Def bar (self): print ' P2-bar ' class C1 (P1,P2): Passclass C2 (P1,P2): Def bar (self): print ' C2-bar ' class D ( C1,C2): passif __name__ = = ' __main__ ': D=d () D.foo () D.bar ()
Results of execution:
P1-foop2-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:
#! /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 what the search order is D=d () D.foo () D.bar ()
Results of execution:
(<class ' __main__. D ';, <class ' __main__. C1 ';, <class ' __main__. C2 ';, <class ' __main__. P1 ';, <class ' __main__. P2 ';, <type ' object ' >) p1-fooc2-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.