david4dev
david4dev

Reputation: 4914

How to avoid infinite recursion with super()?

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?

Upvotes: 28

Views: 6691

Answers (1)

Thomas K
Thomas K

Reputation: 40340

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

Upvotes: 52

Related Questions