如何使用 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)
(为了更好的衡量,使用 super(C,self)
in C).从 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屋!