Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a overwritten parent-method from within a parent-class?

I’d like to call a method, from within a parent-class, without falling back to the method from a child-class. I think an example will make it most clear:

class Parent:
    def calculate(self, n):
        return n + 10

    def print_plus_ten(self, n):
        print(self.calculate(n))

class Child(Parent):
    def calculate(self, n):
        return n + 1

    def print_using_parent(self, n):
        print(super().calculate(n))

If I make a parent-object, my print_plus_ten works as the name implies.

Now, if I make a child-object, the method calculate gets overwritten, and print_plus_ten prints out its argument plus 1. How can I make the function print_plus_ten always call the function calculate from the parent? From the child, it’s easy, because we have super(), like in the example print_using_parent.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there such a similar function to get to the object in which we have our scope itself? If I use super() in Parent, it just gives me Object (which has no attribute calculate)

>Solution :

You would have to hard-code a reference to Parent, as you don’t want to delegate attribute lookup to the object itself. You can use the special name __class__ to avoid duplicating the name Parent in the code.

class Parent:
    def calculate(self, n):
        return n + 10

    def print_plus_ten(self, n):
        print(__class__.calculate(self, n))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading