簡體   English   中英

如何將mixin的引用傳遞給python中的另一個mixin?

[英]How is the reference of mixin pass to another mixin in python?

如果一個類繼承多個類,那么為什么超類可以互相訪問其他超類的功能? 超類從哪里獲取引用?

例如

class A():
    def a_method(self):
        print "I am a"

class B():
    def b_method(self):
        self.a_method()

class test(A, B):
    def test_method(self):
        self.b_method()

if __name__ == "__main__":
    test_instance = test()
    # Will print a_method
    test_instance.test_method()

    test_b = B()

    try:
        # will raise exception
        test_b.b_method()
    except Exception as e:
        print e

當您將一個類定義為從兩個超類繼承時

class test(A, B):

它從兩個超類繼承方法到同一個名稱空間。 因此,可以從test()調用self.a_method()self.b_method() 我想,您的問題是為什么調用self.b_method()可以從test實例而不是B實例工作。 它在test有效,因為兩個方法都在同一個命名空間中,並且當b_method()調用a_method() ,可以從類內部“看到”它,並且調用成功。 當實例化B ,其不從繼承Aa_method()是不可見的,所以產生一個異常。

可以使用dir檢查與類或實例關聯的方法和屬性:

>>> test_instance = test()
>>> dir(test_instance)
['__doc__', '__module__', 'a_method', 'b_method', 'test_method']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM