How to avoid infinite recursion with super()?

Question:

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?

Asked By: david4dev

||

Answers:

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

Answered By: Thomas K