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?
To prevent infinite recursion, you need at least one branch (i.e. of an if/else statement) that does not make a recursive call. Branches without recursive calls are called base cases; branches with recursive calls are called recursive cases. Functions can also be mutually recursive.
The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python's built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.
The “sys” module in Python provides a function called setrecursionlimit() to modify the recursion limit in Python. It takes one parameter, the value of the new recursion limit. By default, this value is usually 10^3.
If a recursion never reaches a base case, it will go on making recursive calls forever and the program will never terminate. This is known as infinite recursion, and it is generally not considered a good idea. In most programming environments, a program with an infinite recursion will not really run forever.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With