调用super的init时Python中的最大递归深度错误.

pro*_*eek 11 python recursion hierarchy superclass

我有一个类层次结构A < - B < - C,在B中,我需要在构造函数中进行一些处理,所以我从这篇文章中想出了这个代码:用__init __()方法理解Python super()

#!/usr/bin/python

class A(object):
    def __init__(self, v, v2):
        self.v = v
        self.v2 = v2

class B(A):
    def __init__(self, v, v2):
        # Do some processing
        super(self.__class__, self).__init__(v, v2)

class C(B):
    def hello():
        print v, v2


b = B(3, 5)
print b.v
print b.v2

c = C(1,2)
print c
Run Code Online (Sandbox Code Playgroud)

但是,我遇到超出最大递归的运行时错误

  File "evenmore.py", line 12, in __init__
    super(self.__class__, self).__init__(v, v2)
RuntimeError: maximum recursion depth exceeded while calling a Python object
Run Code Online (Sandbox Code Playgroud)

可能有什么问题?

Łuk*_*ski 8

首先要考虑的是:C从B继承构造函数(因为它没有在C中定义).

第二件事要考虑: self.__class____init__C类中调用是C,而不是B.

我们来分析一下:

  • C().__init__电话super(self.__class__, self).__init__(v, v2)这决心 super(C, self).__init__(v, v2),这意味着B.__init__(self, v, v2).
  • 传递给的第一个参数B.__init__有一个类型C.super(self.__class__, self).__init__(v, v2)再次解决了B.__init__(self, v, v2).
  • 又一次又一次.还有你的无限递归.