[英]How do I use type hint for multiple classes in a dictionary but they inherit from same parent class?
[英]How to use super() to inherit a particular class from multiple father classes?
我的代碼是這樣的,我想使用super()繼承Papa的功能,該怎么做?
class Mama(object):
def __init__(self):
self.name = 'Mama'
def feature(self):
print "%s have big eyes" % self.name
class Papa(object):
def __init__(self):
self.name = 'Papa'
def feature(self):
print "%s have fierce beards" % self.name
class Offspring(Mama,Papa):
def __init__(self, name):
self.name = name
def feature(self):
super(Offspring, self).feature()
offspring = Offspring('Tommy')
offspring.feature()
# This will result "Tommy have big eyes"
您可以通過繼承改變MRO(方法解析順序) Papa
第一 :
class Offspring(Papa, Mama):
另一種方法是跳過MRO並在Papa
顯式調用(unbound)方法:
class Offspring(Mama, Papa):
def __init__(self, name):
self.name = name
def feature(self):
Papa.feature(self)
喜劇中的所有類都需要使用super
才能通過所有方法。 最終,您將遇到一個問題,即下一個超類是object
,它不具有feature
,因此您還需要檢測到這種情況並忽略它-即,您需要這樣做:
class Mama(object):
def __init__(self):
self.name = 'Mama'
def feature(self):
try:
super(Mama, self).feature()
except AttributeError:
# only superclass is object
pass
print "%s have big eyes" % self.name
class Papa(object):
def __init__(self):
self.name = 'Papa'
def feature(self):
try:
super(Papa, self).feature()
except AttributeError:
# only superclass is object
pass
print "%s have fierce beards" % self.name
class Offspring(Mama,Papa):
def __init__(self, name):
self.name = name
def feature(self):
super(Offspring, self).feature()
除了捕獲AttributeError之外,您還可以創建另一個僅存在的類,以提供feature
(不調用super
)供其他類繼承。 然后,Mama和Papa都繼承該類並重寫feature
,如下所示:
class Grandma(object):
def feature(self):
pass
class Mama(Grandma):
def feature(self):
super(Mama, self).feature()
print "%s have big eyes" % self.name
您可能需要考慮將feature
設為抽象方法 ,以強調它僅在繼承時存在。
無論哪種情況,都將繼續調用下一個方法,直到到達鏈的末尾。 如果Mama
和Papa
都不叫超級,您將在一個電話之后總是停下來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.