[英]How to call the second super method when using multiple inheritance?
class Foo1:
def hi(self, name):
print('Oh hi there %s.' % name)
class Foo2:
def hi(self, name):
print('Hi %s, how ya doing?' % name)
class Bar(Foo1, Foo2):
def hi(self, name):
super(Bar, self).hi(name)
bar = Bar()
bar.hi('John')
輸出:
Oh hi there John.
除了交換“Foo1, Foo2”的順序之外,如何從 Bar 訪問 Foo2 的 super 方法?
如果你想繞過正常的方法解析順序,你就會陷入困境。 任何一個:
假裝成為 MRO 中您真正想要的班級之前的班級:
def hi(self, name): super(Foo1, self).hi(name) # I'm really Bar's method, but lying to say I'm Foo1's
顯式調用您關心的類(手動傳遞self
):
def hi(self, name): Foo2.hi(self, name) # Looking it up directly on the class I want
注意:如果您使用的是 Python 3 並且想要正常的 MRO,則根本不需要將參數傳遞給super()
,這將很好地調用Foo1.hi
:
def hi(self, name):
super().hi(name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.