標籤:python 繼承 類 inheritance
http://blog.csdn.net/pipisorry/article/details/46381341
There are two typical use cases forsuper:
In a class hierarchy withsingle inheritance, super can be used to refer to parent classes withoutnaming them explicitly, thus making the code more maintainable. This useclosely parallels the use ofsuper in 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 languages or languages 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 calls is determined at runtime, because that order adaptsto changes in the class hierarchy, and because that order can includesibling classes that are unknown prior to runtime).
For both use cases,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 Parent1(object): def on_start(self): print(‘do something‘)class Parent2(object): def on_start(self): print(‘do something else‘)class Parent3(object): pass
子類定義1:
class Child(Parent1, Parent2, Parent3): def on_start(self): for base in Child.__bases__: try: base.on_start(self) except 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()
結果輸出:
do something
do something else
"Parent3" does not have an "on_start"
子類定義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.on_start()兩個結果都輸出為: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 functions withsuper
is impossible.
2. 注意子類定義2中的用法1
[Python Multiple Inheritance: call super on all]
注意的問題
按類名訪問
就相當於C語言之前的GOTO
語句...亂跳,然後再用super
按順序訪問,就有問題了。
所以建議就是要麼一直用super
,要麼一直用按照類名訪問
最佳實現:
- 避免多重繼承
- super使用一致
- 不要混用經典類和新式類
- 調用父類的時候注意檢查類層次
[Python類繼承的進階特性]
from:http://blog.csdn.net/pipisorry/article/details/46381341
ref:Python 為什麼要繼承 object 類?
python多繼承