簡體   English   中英

如何使用 super() 從 python 中的不同類中執行多個 inheritance?

[英]How to do multiple inheritance from different classes in python using super()?

可以說我們有不同類型的人,鋼琴家,程序員和多才多藝的人。 那么,我該如何繼承呢? 目前此代碼給出錯誤 Multitalented has no attribute canplaypiano。

class Pianist:
    def __init__(self):
        self.canplaypiano=True

class Programer:
    def __init__(self):
        self.canprogram=True

class Multitalented(Pianist,Programer):
    def __init__(self):
        self.canswim=True
        super(Pianist,self).__init__()
        super(Programer,self).__init__()

Raju=Multitalented()

print(Raju.canswim)
print(Raju.canprogram)
print(Raju.canplaypiano)

另外請提及一些關於 python 繼承/super() 的寫得很好的文章,我找不到一個完美的文章,有清晰的解釋。 謝謝你。

協作多 inheritance 中涉及的所有類都需要使用super ,即使static基礎 class 只是object

class Pianist:
    def __init__(self):
        super().__init__()
        self.canplaypiano=True

class Programer:
    def __init__(self):
        super().__init__()
        self.canprogram=True

class Multitalented(Pianist,Programer):
    def __init__(self):
        super().__init__()
        self.canswim=True
        
Raju=Multitalented()

print(Raju.canswim)
print(Raju.canprogram)
print(Raju.canplaypiano)

初始化程序的運行順序由Multitalented的方法解析順序決定,您可以通過更改Multitalented列出其基類的順序來影響該順序。

第一篇(如果不是最好的話)要閱讀的文章是 Raymond Hettinger 的Python 的super()被認為是超級的! ,其中還包括有關如何調整自己使用super的類以用於協作多繼承層次結構的建議,以及有關如何覆蓋使用super的 function 的建議(簡而言之,您不能更改簽名)。

不要用顯式的父類調用super 在現代 python 版本(不確切知道從哪個版本開始)中,您調用super而不使用參數。 也就是說,在您的情況下,您應該只有一行,而不是兩行:

super().__init__()

In somewhat older versions you need to provide the class explicitly, however you should provide the class of "current" object, and the super function takes care of finding out the parent classes. 在你的情況下,它應該是:

super(Multitalented, self).__init__()

暫無
暫無

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

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