This article mainly introduces multiple inheritance instances in python. This article focuses on the order of finding the parent class, which is divided into classic class and new class. For more information, see python and C ++, supports multi-inheritance. Although the concept is easy, it is difficult for a subclass to call an attribute that is not defined by itself. In what order does it go to the parent class for searching, in particular, multiple parent classes contain the same name attribute.
For classic classes and new classes, the order of search for attributes is different. Now let's take a look at the two different performances of classic and new style:
Classic:
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 ()
Execution result:
The Code is as follows:
P1-foo
P2-bar
Draw a picture of the Code instance for ease of understanding:
From the output results of the classic category above,
When instance D calls foo (), the search order is D => C1 => P1,
When bar () is called by instance D, the search order is D => C1 => P1 => P2
Summary: The typical search method is to search for attributes in the "from left to right, depth first" mode. D. First, check whether the foo method exists. If not, check whether the method exists in C1, the nearest parent class. If not, continue to look up until the method is found in P1, the search is complete.
New category:
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 _ # Only the new class has the _ mro _ attribute, which tells the query order.
D = D ()
D. foo ()
D. bar ()
Execution result:
The Code is as follows:
( , , , , , )
P1-foo
C2-bar
From the output results of the new class above,
When the instance D calls foo (), the search order is D => C1 => C2 => P1
When bar () is called by instance D, the search order is D => C1 => C2
Conclusion: The new category search method uses the "Breadth First" method to search for attributes.