如何使用 super() 从 python 中的不同类进行多重继承?



假设我们有不同类型的人,钢琴家,程序员和多才多艺的人。 那么,我如何像这样继承呢?目前此代码给出错误 多才多艺没有属性 canplaypiano。

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继承/super()的写得很好的文章,我找不到一篇解释清晰的完美文章。 谢谢。

所有参与协同多重继承的类都需要使用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 Hettinger的Python的super()被认为是Super!,其中还包括有关如何调整自己不使用的类的建议super用于协作多重继承层次结构,以及如何覆盖使用super的函数的建议(简而言之,你不能更改签名)。

不要使用显式父类调用super。在现代 python 版本中(不知道确切是从哪个版本开始),您调用不带参数的super。也就是说,在您的情况下,您应该只有一行,而不是两行:

super().__init__()

在较旧的版本中,您需要显式提供类,但是您应该提供"当前"对象的类,super函数负责找出父类。在您的情况下,它应该是:

super(Multitalented, self).__init__()

最新更新