編輯:感謝您的答復。這是我用來學習的網站上的練習,我沒有設計它。我想確認 Wolf.action(self) 是一個靜態呼叫,并詢問如果由于 MRO(在 Diamond 方案中)只能將 Dog 類的方法與 super() 一起使用,為什么要讓 Wolf 繼承自 Animal。因為您只能將 super() 與定義中列出的第一個類一起使用,所以使子類繼承自多個獨立類有什么意義嗎?跟進口有關系嗎?
所以,在這段代碼中:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def action(self):
print("{} wags tail. Awwww".format(self.name))
class Wolf(Animal):
def action(self):
print("{} bites. OUCH!".format(self.name))
class Hybrid(Dog, Wolf):
def action(self):
super().action()
Wolf.action(self)
my_pet = Hybrid("Fluffy")
my_pet.action() # Fluffy wags tail. Awwww
# Fluffy bites. OUCH!
為什么我必須提供selfinWolf.action(self)而不是 in super().action()?為什么我不能做Wolf.action()?
我猜這只是一個靜態呼叫,因此這就是我需要傳遞一個顯式引數的原因。但是,在這種情況下,多重繼承有什么意義呢?如果Hybrid不繼承自不一樣Wolf嗎?
我已經閱讀了一些其他主題,但其中大多數都在談論 MRO,而這不是我要尋找的答案。
提前致謝。
uj5u.com熱心網友回復:
Wolf.actionself是實際函式,而不是在您嘗試呼叫它時隱式包含的系結方法。
但是,如果使用super得當,則不需要顯式呼叫Wolf.action.
class Animal:
def __init__(self, name):
self.name = name
def action(self):
pass
class Dog(Animal):
def action(self):
super().action()
print("{} wags tail. Awwww".format(self.name))
class Wolf(Animal):
def action(self):
super().action()
print("{} bites. OUCH!".format(self.name))
class Hybrid(Wolf, Dog):
pass
my_pet = Hybrid("Fluffy")
my_pet.action() # Fluffy wags tail. Awwww
# Fluffy bites. OUCH!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/536992.html
標籤:Python班级自己
