1

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!!!

0

1 Answer 1

3

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.