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