简体   繁体   中英

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 .

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 )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM