繁体   English   中英

如何使用 super() 从 python 中的不同类中执行多个 inheritance?

[英]How to do multiple inheritance from different classes in python using super()?

可以说我们有不同类型的人,钢琴家,程序员和多才多艺的人。 那么,我该如何继承呢? 目前此代码给出错误 Multitalented has no attribute 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() 的写得很好的文章,我找不到一个完美的文章,有清晰的解释。 谢谢你。

协作多 inheritance 中涉及的所有类都需要使用super ,即使static基础 class 只是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的 function 的建议(简而言之,您不能更改签名)。

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

super().__init__()

In somewhat older versions you need to provide the class explicitly, however you should provide the class of "current" object, and the super function takes care of finding out the parent classes. 在你的情况下,它应该是:

super(Multitalented, self).__init__()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM