如何避免使用super()进行无限递归?

dav*_*dev 28 python oop multiple-inheritance super

我有这样的代码:

class A(object):
    def __init__(self):
          self.a = 1

class B(A):
    def __init__(self):
        self.b = 2
        super(self.__class__, self).__init__()

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

实例化B按预期工作但实例化C无限递归并导致堆栈溢出.我怎么解决这个问题?

Tho*_*s K 49

实例化C调用时B.__init__,self.__class__仍然是C,所以super()调用将它带回B.

调用super()时,直接使用类名.所以在B中,调用super(B, self),而不是super(self.__class__, self)(并且super(C, self)在C中使用).从Python 3开始,您可以使用不带参数的super()来实现相同的功能