隐式调用父类初始值设定项

Mat*_*ner 7 python constructor python-2.x super method-resolution-order

class A(object):
    def __init__(self, a, b, c):
        #super(A, self).__init__()
        super(self.__class__, self).__init__()


class B(A):
    def __init__(self, b, c):
        print super(B, self)
        print super(self.__class__, self)
        #super(B, self).__init__(1, b, c)
        super(self.__class__, self).__init__(1, b, c)

class C(B):
    def __init__(self, c):
        #super(C, self).__init__(2, c)
        super(self.__class__, self).__init__(2, c)
C(3)
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,注释掉的__init__调用看起来是进行超类初始化的普遍接受的"智能"方式.但是,如果类层次结构可能会发生变化,我一直在使用未注释的表单,直到最近.

看来,在B上面层次结构中对超级构造函数的B.__init__调用,再次调用,self.__class__实际上C并不B像我一直假设的那样.

在Python-2.x中是否有某些方法可以在调用超级构造函数时保持正确的MRO(关于以正确的顺序初始化所有父类),而不是命名当前类(Bin in super(B, self).__init__(1, b, c))?

Mar*_*nas 3

简短的回答:不,在 Python 2.x 中没有办法用__init__右父类的正确参数隐式调用右派。

顺便说一句,这里显示的代码是不正确的:如果您使用 super()。__init__,那么层次结构中的所有类的__init__方法都必须具有相同的签名。否则,如果您引入使用多重继承的新子类,您的代码可能会停止工作。

有关问题的详细说明(带图片),请参阅http://fuhm.net/super-harmful/ 。