为具有super的多个父类调用init?

2024-06-26 13:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Can Super deal with multiple inheritance?

Python继承?我有一个类结构(如下所示),希望子类调用双亲的__init__。这是以一种“超级”的方式做的,还是一个糟糕的主意?

class Parent1(object):
    def __init__(self):
        self.var1 = 1

class Parent2(object):
    def _init__(self):
        self.var2 = 2

class Child(Parent1, Parent2):
    def __init__(self):
        ## call __init__ of Parent1
        ## call __init__ of Parent2
        ## super(Child, self).__init__()

Tags: ofselfchildobjectinitdefcallcan
3条回答

super()的思想是,您不必费心分别调用两个超类__init__()方法——只要您正确使用它,super()就会处理它——请参阅Raymond Hettinger's "Python’s super() considered super!"以获取解释。

也就是说,我经常发现构造函数调用的super()的缺点大于优点。例如,所有构造函数都需要提供一个附加的**kwargs参数,所有类都必须协作,非协作的外部类需要一个包装器,您必须注意每个构造函数参数名称在类之间都是唯一的,等等

因此,我认为更容易显式地命名要为构造函数调用调用的基类方法:

class Child(Parent1, Parent2):
    def __init__(self):
        Parent1.__init__(self)
        Parent2.__init__(self)

不过,对于有保证原型的函数,比如__getattr__(),我确实使用super()。在这些情况下没有缺点。

通过super调用不会调用所有父级,而是调用MRO链中的下一个函数。要使其正常工作,您需要在所有__init__中使用super

class Parent1(object):
    def __init__(self):
        super(Parent1, self).__init__()
        self.var1 = 1

class Parent2(object):
    def __init__(self):
        super(Parent2, self).__init__()
        self.var2 = 2

class Child(Parent1, Parent2):
    def __init__(self):
        super(Child, self).__init__()

在Python 3中,可以使用super(),而不是super(type, instance)

您可以直接用Parent.__init__(self)调用它们:

class Parent1(object):
    def __init__(self):
        self.var1 = 1

class Parent2(object):
    def __init__(self):
        self.var2 = 2

class Child(Parent1, Parent2):
    def __init__(self):
        Parent1.__init__(self)
        Parent2.__init__(self)
        print(self.var1, self.var2)

相关问题 更多 >