我们有不同的人,钢琴家,程序员和多才多艺的人。那么,我怎么继承这样的遗产呢?目前,这个代码给错误,多才多艺没有属性弹钢琴。
class Pianist:
def __init__(self):
self.canplaypiano=True
class Programer:
def __init__(self):
self.canprogram=True
class Multitalented(Pianist,Programer):
def __init__(self):
self.canswim=True
super(Pianist,self).__init__()
super(Programer,self).__init__()
Raju=Multitalented()
print(Raju.canswim)
print(Raju.canprogram)
print(Raju.canplaypiano)另外,请提到一些写得很好的关于python继承/超级()的文章,我找不到一篇有明确解释的完美文章。谢谢你。
发布于 2022-01-10 14:37:12
涉及协作多重继承的所有类都需要使用super,即使静态基类只是object。
class Pianist:
def __init__(self):
super().__init__()
self.canplaypiano=True
class Programer:
def __init__(self):
super().__init__()
self.canprogram=True
class Multitalented(Pianist,Programer):
def __init__(self):
super().__init__()
self.canswim=True
Raju=Multitalented()
print(Raju.canswim)
print(Raju.canprogram)
print(Raju.canplaypiano)初始化程序运行的顺序由Multitalented的方法解析顺序决定,您可以通过更改Multitalented列出其基类的顺序来影响该顺序。
第一篇(如果不是最好的话)文章是Raymond的Python's super() Considered Super!,它还包括关于如何调整不使用super的类以便在协作的多继承层次结构中使用的建议,以及关于如何覆盖使用super的函数的建议(简而言之,您不能更改签名)。
发布于 2022-01-10 14:14:27
不要使用显式父类调用super。在现代python版本中(不知道具体从哪个版本开始),您可以在没有参数的情况下调用super。也就是说,在您的情况下,您应该只有一行,而不是两行:
super().__init__()在稍早的版本中,您需要显式地提供类,但是您应该提供“当前”对象的类,super函数负责查找父类。在你的情况下,应该是:
super(Multitalented, self).__init__()https://stackoverflow.com/questions/70653674
复制相似问题