我的目標:在呼叫 Parent2 類中的 [identify] 方法的子類中創建名為 [identify2] 的方法。這必須使用 super() 關鍵字來完成。
我的問題:兩個父類中的方法名稱相同。但我只想與使用 super() 關鍵字的 parent2 類的方法有關。我該怎么辦?
class Parent1:
def identify(self):
return "This method is called from Parent1"
class Parent2:
def identify(self):
return "This method is called from Parent2"
# declare child class here
class child(Parent1, Parent2):
def identify(self):
return "This method is called from Child"
def identify2(self):
super().identify() # I want to call the method of Parent2 class, how?
child_object = child()
# Expected output:
print( child_object.identify() ) # This method is called from Child
print( child_object.identify2() ) # This method is called from Parent2
uj5u.com熱心網友回復:
super可以使用型別和物件引數呼叫,請參閱檔案。type 引數確定在 mro 順序中的哪個類之后開始搜索方法。在這種情況下,要獲取Parent2搜索方法應該在以下之后開始Parent1:
class Parent1:
def identify(self):
return "This method is called from Parent1"
class Parent2:
def identify(self):
return "This method is called from Parent2"
# declare child class here
class Child(Parent1, Parent2):
def identify(self):
return "This method is called from Child"
def identify2(self):
return super(Parent1, self).identify()
child_object = Child()
# Expected output:
print( child_object.identify() ) # This method is called from Child
print( child_object.identify2() ) # This method is called from Parent2
這給出:
This method is called from Child
This method is called from Parent2
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/341848.html
