如何避免 super() 无限递归?

发布于 2024-10-04 06:07:37 字数 360 浏览 1 评论 0原文

我有这样的代码:

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 无限递归并导致堆栈溢出。我该如何解决这个问题?

I have code like this:

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__()

Instantiating B works as expected but instantiating C recursed infinitely and causes a stack overflow. How can I solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

季末如歌 2024-10-11 06:07:37

当实例化 C 调用 B.__init__ 时,self.__class__ 仍将是 C,因此 super() 调用将其带回到 B。

调用 super() 时,使用直接类名。因此,在 B 中,调用 super(B, self),而不是 super(self.__class__, self)(为了更好地衡量,请使用 super(C, self) 在 C) 中。从 Python 3 开始,您可以使用不带参数的 super() 来实现相同的效果

When instantiating C calls B.__init__, self.__class__ will still be C, so the super() call brings it back to B.

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文