Python - 为多个父类调用 __init__ [英] Python - Calling __init__ for multiple parent classes

查看:64
本文介绍了Python - 为多个父类调用 __init__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Python 3.

我有一个类 X 扩展了 YZ:

I have a class X that extends both Y and Z:

class X(Y, Z):
    def __init__(self):
    # Call Y's __init__
    # Call Z's __init
    pass

我需要在 YZ 上从 __init__ 上调用 __init__ X.什么是最好的方法来做到这一点?

I need to call __init__ on both Y and Z from the __init__ on X. What would be the best way to do this?

推荐答案

这完全取决于 YZ 是否被设计工作与多重继承合作.如果是,那么您应该可以只使用 super:

This depends entirely on whether Y and Z were designed to work cooperatively with multiple inheritance. If they are, then you should be able to just use super:

class X(Y, Z):
    def __init__(self):
        super().__init__()

当我说 YZ 需要设计为与多重继承协同工作时,我的意思是他们还必须在他们的 __init__<中调用 super/code> 方法:

When I say that Y and Z need to be designed to work cooperatively with multiple inheritance, I mean that they must also call super in their __init__ methods:

class Y:
    def __init__(self):
        print('Y.__init__')
        super().__init__()

class Z:
    def __init__(self):
        print('Z.__init__')
        super().__init__()

他们也应该有一些策略来处理不同的参数,因为一个类的(特别是构造函数)在它们接受的关键字参数方面经常不同.在这一点上,值得一读超级被认为是超级!超级被认为有害了解有关超级的一些常见习语和陷阱.

They should also have some strategy for handling different arguments since (particularly the constructor) of a class frequently differ in which keyword arguments that they accept. At this point, it's worth reading Super considered super! and Super considered harmful to understand some common idioms and pitfalls regarding super.

如果您不知道 YZ 是否是为协作多重继承而设计的,那么最安全的方法是假设它们不是.

If you don't know whether Y and Z were designed for cooperative multiple inheritance, then the safest recourse is to assume that they weren't.

如果这些类不是为使用协作多重继承而设计的,那么您需要开始轻装上阵(您处于危险境地).您可以单独调用每个__init__:

If the classes aren't designed to work with cooperative multiple inheritance, then you need to start stepping lightly (you're in dangerous waters). You can call each __init__ individually:

class X(Y, Z):
    def __init__(self):
        Y.__init__(self)
        Z.__init__(self)

但实际上最好不要使用多重继承,而是选择不同的范式(例如组合).

But really it's probably better to not use multiple inheritance and instead choose a different paradigm (e.g. composition).

这篇关于Python - 为多个父类调用 __init__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆