![](/img/trans.png)
[英]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.