Yehoshaphat Schellekens
Yehoshaphat Schellekens

Reputation: 2385

Calling Grandfather class method results in RecursionError (maximum recursion depth exceeded)

Im trying to call a grandfather method and getting the following error (RecursionError):

class GrandParent:
    def get_data(self):
        return 5


class Parent(GrandParent):
    def get_data(self):
        return super(self.__class__, self).get_data()


class Child(Parent):
    def get_other_data(self):
        d = self.get_data()
        print(d)
        return d


demo = Child()
res = demo.get_other_data()
print('done')

And i'm getting the following error:

RecursionError: maximum recursion depth exceeded while calling a Python object

Why is that?

I tried to look at this one: RecursionError: maximum recursion depth exceeded while calling a Python object(Algorithmic Change Required) but it seems like we shouldn't have any recursion issues.

Thanks in advance!!!

Upvotes: 1

Views: 238

Answers (1)

Gulzar
Gulzar

Reputation: 27946

self is dynamicly binded, meaning it has the type of the actual created object, in this case Child.

Here is what happens in the case above:

class Parent(GrandParent):
    def get_data(self):
        return super(self.__class__, self).get_data()

evaluates to

class Parent(GrandParent):
    def get_data(self):
        return super(Child, self).get_data()

which is

class Parent(GrandParent):
    def get_data(self):
        return Parent.get_data(self)

You can now see why this is an endless recursion.


Python 2.7 best practice:

class Parent(GrandParent):
    def get_data(self):
        return super(Parent, self).get_data()

Python 3+:

class Parent(GrandParent):
    def get_data(self):
        return super().get_data()

Upvotes: 3

Related Questions