how to refer to a parent method in python?

Question:

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.

Asked By: user1111042

||

Answers:

Use super:

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

Or in python 3, it’s just:

return 7 * super().f(num)
Answered By: tzaman
class B(A):
    def f(self, num):
        return 7 * super(B, self).f(num)
Answered By: wong2

If you know you want to use A you can also explicitly refer to A in this way:

class B(A):
    def f(self,num): 
        return 7 * A.f(self,num)

remember you have to explicitly give the self argument to the member function A.f()

Answered By: jimifiki

Why not keep it simple?

class B(A):
    def f(self, num):
        return 7 * A.f(self, num)
Answered By: pillmuncher

you can use super or if you can be more explicit and do something like this.

class B(A):
  def f(self, num):
    return 7 * A.f(self, num)
Answered By: Doboy

In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:

Python-2.x

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(B, self).__init__()

Python-3.x

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super().__init__()

super() is now equivalent to super(<containing classname>, self) as per the docs.

Answered By: Aidan Gomez

Check out my answer at Call a parent class's method from child class in Python?.

It’s a slight twist on some others here (that don’t use super).

Answered By: BuvinJ
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.