標籤:nbsp argument color list translate 使用 hiera 調用 types
https://docs.python.org/2/tutorial/classes.html#multiple-inheritance
http://www.jackyshen.com/2015/08/19/multi-inheritance-with-super-in-Python/
http://python.jobbole.com/85685/
在多繼承中,如何訪問父類中某個屬性,是按照__mro__中的順序確定的。
關於super(),原型是這樣的:
super
(type[, object-or-type])
note:If the second argument is omitted, the super object returned is unbound. If the second argument is an object, isinstance(obj, type)
must be true. If the second argument is a type, issubclass(type2, type)
must be true (this is useful for classmethods).
在初始化的時候,如果使用了super()(ref:https://docs.python.org/2/library/functions.html#super),
那麼會按照__mro__中的順序初始化遇到的第一個父類
如果想初始化所有父類,就要用顯式的方法了,比如,定義類:
A, B, C(A, B)
那麼在C中可以這樣初始化父類A:
A.__init__(self)
假如沒有調用A的建構函式,那麼在A的建構函式中定義的變數就不能訪問,儘管C是A的子類
因為並沒有把A的建構函式中定義的變數綁定在C的執行個體上
但是A的方法還是可以調用,調用的順序由__mro__決定:
class A(object): def __init__(self): self.a = 1 print ‘A‘ def sing(self): print ‘sing A‘class B(object): def __init__(self): print ‘B‘class C(A, B): def __init__(self): print ‘C‘c = C()c.sing() # okprint c.a # error
MRO的全稱是method resolution order, 它定義了一種在多重繼承的情況下依次訪問父類的順序
文檔裡(https://docs.python.org/2/library/functions.html#super)這樣描述MRO:
The __mro__
attribute of the type lists the method resolution search order used by both getattr()
and super()
. The attribute is dynamic and can change whenever the inheritance hierarchy is updated.
目前Python2.7中的新式類,Python3中的類擷取MRO使用的是C3演算法(ref:https://en.wikipedia.org/wiki/C3_linearization)
Python多繼承中的一些問題