Maximum Python recursion depth error when calling super init.

I have a class hierarchy A <-B <-C, in B, I need some processing in the constructor, so I came up with this code from this post: Understanding Python super () using __init __ () methods

#!/usr/bin/python class A(object): def __init__(self, v, v2): self.v = v self.v2 = v2 class B(A): def __init__(self, v, v2): # Do some processing super(self.__class__, self).__init__(v, v2) class C(B): def hello(): print v, v2 b = B(3, 5) print bv print b.v2 c = C(1,2) print c 

However, I have a runtime error from maximum recursion exceeded

  File "evenmore.py", line 12, in __init__ super(self.__class__, self).__init__(v, v2) RuntimeError: maximum recursion depth exceeded while calling a Python object 

What could be wrong?

+8
python recursion superclass hierarchy
source share
2 answers

The first thing to consider: C inherits the constructor from B (because it is not defined in C).

Second: self.__class__ in __init__ call in class C is C, not B.

Let's analyze:

  • C().__init__ calls super(self.__class__, self).__init__(v, v2) , which is allowed by super(C, self).__init__(v, v2) , which means B.__init__(self, v, v2) .
  • The first argument passed to B.__init__ is of type C super(self.__class__, self).__init__(v, v2) again allowed B.__init__(self, v, v2) .
  • And again, and again, and again. And there is your endless recursion.
+6
source share

Providing the first parameter is super since the class name solves this problem.

 class B(A): def __init__(self, v, v2): # Do some processing super(B, self).__init__(v, v2) 
+1
source share

All Articles