Python:当超类接受不同的参数时进行初始化的正确方法吗? [英] Python: Correct way to initialize when superclasses accept different arguments?
问题描述
如果我有三个这样的课程:
If I've got three classes like this:
class BaseClass(object):
def __init__(self, base_arg, base_arg2=None):
...
class MixinClass(object):
def __init__(self, mixin_arg):
...
class ChildClass(BaseClass, MixinClass):
def __init__(self, base_arg, mixin_arg, base_arg2=None):
???
初始化MixinClass
和BaseClass
的正确方法是什么?
What is the correct way to initialize MixinClass
and BaseClass
?
它看起来不像我可以使用super
那样,因为MixinClass
和BaseClass
都接受不同的参数……而两个调用MixinClass.__init__(...)
和BaseClass.__init__(...)
将可能会导致钻石继承问题super
旨在防止这种情况发生.
It doesn't look like I can use super
because the MixinClass
and the BaseClass
both accept different arguments… And two calls, MixinClass.__init__(...)
and BaseClass.__init__(...)
, will could cause the diamond inheritence problem super
is designed to prevent.
推荐答案
基本上,在Python中,您不能安全地支持此类继承.幸运的是,您几乎不需要,因为大多数方法都不关心是什么,只是它支持特定的接口.最好的选择是使用组合或聚合:让您的类继承自父类之一,并包含对第二个类的实例的引用.只要您的课程支持第二个课程的接口(并将消息转发到所包含的实例),就可以正常工作.
Basically, in Python, you can't support this type of inheritance safely. Luckily you almost never need to, since most methods don't care what something is, only that it supports a particular interface. Your best bet is to use composition or aggregation: have your class inherit from one of the parent classes, and contain a reference to an instance of the second class. As long as your class supports the interface of the second class (and forwards messages to the contained instance) this will probably work out fine.
在上面的示例中(两个类都从object
继承),您可以(可能)安全地从两个类中继承,并使用MixinClass.__init__
和BaseClass.__init__
调用这两个构造函数.但是请注意,如果父类在其构造函数中调用super
,则这样做是不安全的.一个好的经验法则是,如果父类使用super
,则使用super
,如果父类使用__init__
,则使用__init__
,希望您永远不必从必须继承两个选择了不同方法的类中继承进行初始化.
In the above example (where both classes inherit from object
) you can (probably) safely just inherit from both classes and call both constructors using MixinClass.__init__
and BaseClass.__init__
. But note that's not safe to do if the parent classes call super
in their constructors. A good rule of thumb is to use super
if the parent classes use super
, and __init__
if the parent classes use __init__
, and hope you're never trapped having to inherit from two classes which chose different methods for initialization.
这篇关于Python:当超类接受不同的参数时进行初始化的正确方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!