Python multi-inheritance, python inheritance
Http://blog.csdn.net/pipisorry/article/details/46381341
There are two typical use casesSuper:
In a class hierarchy withsingle inheritance,SuperCan be used to refer to parent classes withoutnaming them explicitly, thus making the code more maintainable. This useclosely parallels the useSuperIn other programming languages.
The second use case is to support cooperative multiple inheritance in adynamic execution environment. this use case is unique to Python and isnot found in statically compiled ages or ages that only supportsingle inheritance. this makes it possible to implement "diamond diagrams" where multiple base classes implement the same method. good design dictatesthat this method have the same calling signature in every case (because theorder of CILS is determined at runtime, because that order adaptsto changes in the class hierarchy, and because that order can have desibling classes that are unknown prior to runtime ).
For both use case, a typical superclass call looks like this:
class C(B): def method(self, arg): super().method(arg) # This does the same thing as:super(C, self).method(arg)
[super
]
Class inheritance instance
Parent class definition:
class Parent1(object): def on_start(self): print('do something')class Parent2(object): def on_start(self): print('do something else')class Parent3(object): pass
Subclass Definition 1:
Class Child (Parent1, Parent2, Parent3): def on_start (self): for base in Child. _ bases __: try: base. on_start (self) failed t AttributeError: # handle that one of those does not have that method print ('"{}" does not have an "on_start "'. format (base. _ name __))Child().on_start() # c = Child(); c.on_start()
Result output:
Do something
Do something else
"Parent3" does not have an "on_start"
Subclass Definition 2
Class Child (Parent1, Parent2): def on_start (self): super (Child, self ). on_start () super (Parent1, self ). on_start () class Child (Parent1, Parent2): def on_start (self): Parent1.on _ start (self) Parent2.on _ start (self) Child (). on_start () # c = Child (); c. the output of on_start () is do somethingdo something else.
Note:
1. since both of the parents implements the same method,super
Will just be the same as the first parent inherited, from left to right (for your code,Parent1
). Calling two functionssuper
Is impossible.
2. Pay attention to the usage 1 in subclass Definition 2.
[Python Multiple Inheritance: call super on all]
Notes
Access by Class Name
It is equivalentGOTO
Statement...super
There is a problem with sequential access.
Therefore, we recommend that you always usesuper
, Or always useAccess by Class Name
Best Practice: [advanced features of Python class inheritance]
From: http://blog.csdn.net/pipisorry/article/details/46381341
Ref: Why does Python inherit object classes?