28

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?

david4dev
  • 4,854
  • 2
  • 28
  • 35

1 Answers1

51

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

Thomas K
  • 39,200
  • 7
  • 84
  • 86
  • First of all... call init with super is a major problem that the internet has decided must exists. It works the Thomas is describing ... however, why are you running a super with an init? That's not what it is intended for. (Damn OK as default for enter)

    Just think about this ... when you super init ... you call the base classes init, possibly overwriting all the work you have done. If you insist on use super with init, do it correctly.
    –  Dec 08 '10 at 17:56
  • Prof. Ebral, please tell us the correct way to use it if we must. – nmz787 Jun 24 '14 at 03:22
  • 1
    @nmz787: call to super should be done before performing local initialisations, the questions does it the other way around... Well! I should probably edit the question as it's bad practice and shouldn't be left as example. – kriss Sep 08 '15 at 09:57