Python多繼承中的一些問題

來源:互聯網
上載者:User

標籤: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多繼承中的一些問題

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.