【问题标题】:How to do multiple inheritance from different classes in python using super()?如何使用 super() 从 python 中的不同类进行多重继承?
【发布时间】:2022-01-10 14:06:41
【问题描述】:

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

【问题讨论】:

标签: python inheritance multiple-inheritance


【解决方案1】:

所有涉及协同多重继承的类都需要使用super,即使static基类只是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's super() Considered Super!,其中还包括有关如何调整 自己使用 super 的类以用于合作社的建议多重继承层次结构,以及关于如何覆盖使用super 的函数的建议(简而言之,您不能更改签名)。

【讨论】:

    【解决方案2】:

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

    super().__init__()
    

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

    super(Multitalented, self).__init__()
    

    【讨论】:

    • “(不知道是从哪个版本开始的)”Since Python 3.0
    • 您仍然可以使用显式参数调用它(在极少数情况下它是必要的)。 Python 3 简单地添加了足够的编译器魔法来在通常情况下提供正确的“默认值”。
    猜你喜欢
    • 2020-11-27
    • 2020-05-15
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    相关资源
    最近更新 更多