可以說我們有不同型別的人,鋼琴家,程式員和多才多藝的人。那么,我該如何繼承呢?目前此代碼給出錯誤 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() 的文章,我找不到一篇解釋清楚的完美文章。謝謝。
uj5u.com熱心網友回復:
所有涉及協作多重繼承的類都需要使用super,即使是靜態基類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's super()Considered Super!,其中還包括有關如何調整自己不使用的類以super在協作多繼承層次結構中使用的建議,以及有關如何覆寫使用的函式的建議super(簡而言之,您不能更改簽名) .
uj5u.com熱心網友回復:
不要super使用顯式父類呼叫。在現代 python 版本中(不確切知道從哪個版本開始),您在super沒有引數的情況下呼叫。也就是說,在您的情況下,您應該只有一行,而不是兩行:
super().__init__()
在較舊的版本中,您需要顯式提供類,但是您應該提供“當前”物件的類,并且該super函式負責查找父類。在你的情況下,它應該是:
super(Multitalented, self).__init__()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407829.html
標籤:
上一篇:使用final的執行緒安全
