how to refer to a parent method in python?

user1111042 picture user1111042 · Feb 19, 2012 · Viewed 60.6k times · Source

Suppose I have two classes (one a parent and one a subclass). How do I refer to a method in the parent class if the method is also defined in the subclass different?

Here is the code:

class A:
    def __init__(self, num):
        self.value=num
    def f(self, num):
        return self.value+2
class B(A):
    def f(self, num):
        return 7*self.f(num)

In the very last line, I want to refer to the parent class A with the "self.f(num)" command, not the method itself in B which would create an infinite recursion. Thank you in advance.

Answer

tzaman picture tzaman · Feb 19, 2012

Use super:

return 7 * super(B, self).f(num)

Or in python 3, it's just:

return 7 * super().f(num)