调用super的init时,Python中的最大递归深度错误. [英] Maximum recursion depth error in Python when calling super's init.
本文介绍了调用super的init时,Python中的最大递归深度错误.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类层次结构A<-B<-C,在B中,我需要在构造函数中进行一些处理,因此我从这篇文章中得出了以下代码:
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
怎么了?
推荐答案
首先要考虑的是:C从B继承构造函数(因为它不在C中定义).
First thing to consider: C inherits constructor from B (because it's not defined in C).
要考虑的第二件事:
C类中__init__
调用中的self.__class__
是C,而不是B.
Second thing to consider:
self.__class__
in __init__
invocation in C class is C, not 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)
. - 一次又一次,一次又一次.还有无限的递归.
C().__init__
callssuper(self.__class__, self).__init__(v, v2)
which is resolved tosuper(C, self).__init__(v, v2)
which meansB.__init__(self, v, v2)
.- First argument passed to
B.__init__
has a typeC
.super(self.__class__, self).__init__(v, v2)
is again resolved toB.__init__(self, v, v2)
. - And again, and again, and again. And there is your infinite recursion.
这篇关于调用super的init时,Python中的最大递归深度错误.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文