如何避免使用super()进行无限递归? [英] How to avoid infinite recursion with 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__()
实例化B可以按预期工作,但是实例化C无限递归并导致堆栈溢出.我该如何解决?
Instantiating B works as expected but instantiating C recursed infinitely and causes a stack overflow. How can I solve this?
推荐答案
实例化C调用B.__init__
时,self.__class__
仍为C,因此super()调用将其带回B.
When instantiating C calls B.__init__
, self.__class__
will still be C, so the super() call brings it back to B.
在调用super()时,请直接使用类名.因此,在B中,调用super(B, self)
,而不是super(self.__class__, self)
(并且最好在C中使用super(C, self)
).从Python 3开始,您可以只使用不带参数的super()来实现相同的目的
When calling super(), use the class names directly. So in B, call super(B, self)
, rather than super(self.__class__, self)
(and for good measure, use super(C, self)
in C). From Python 3, you can just use super() with no arguments to achieve the same thing
这篇关于如何避免使用super()进行无限递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!