Maximum recursion depth error in Python when calling super's init. [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-12-21 08:08:22

问题


I have a class hierarchy A <- B <- C, in B, I need some processing in the constructor, so I came up with this code from this post: Understanding Python super() with __init__() methods

#!/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

However, I have an runtime error from maximum recursion exceeded

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

What might be wrong?


回答1:


First thing to consider: C inherits constructor from B (because it's not defined in C).

Second thing to consider: self.__class__ in __init__ invocation in C class is C, not B.

Let's analyze:

  • C().__init__ calls super(self.__class__, self).__init__(v, v2) which is resolved to super(C, self).__init__(v, v2) which means B.__init__(self, v, v2).
  • First argument passed to B.__init__ has a type C. super(self.__class__, self).__init__(v, v2) is again resolved to B.__init__(self, v, v2).
  • And again, and again, and again. And there is your infinite recursion.



回答2:


Giving the first parameter of super as the class name solves this issue.

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


来源:https://stackoverflow.com/questions/32831150/maximum-recursion-depth-error-in-python-when-calling-supers-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!