我的代码是这样的,我想用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"
答案 0 :(得分:4)
您可以先从Papa
继承来更改MRO(方法解析顺序):
class Offspring(Papa, Mama):
另一种方法是跳过MRO并在Papa
上明确调用(未绑定)方法:
class Offspring(Mama, Papa):
def __init__(self, name):
self.name = name
def feature(self):
Papa.feature(self)
答案 1 :(得分:0)
heirachy中的所有类都需要使用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
都没有调用超级,则在一次通话后您将始终停止。