[ACCEPTED]-how to refer to a parent method in python?-polymorphism

Accepted answer
Score: 41

Use super:

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

Or in python 3, it's just:

return 7 * super().f(num)

0

Score: 41

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

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

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

Score: 6

In line with the other answers, there are 4 multiple ways to call super class methods 3 (including the constructor), however in 2 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 1 now equivalent to super(<containing classname>, self) as per the docs.

Score: 2

Why not keep it simple?

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

0

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

0

Score: 1

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

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

Check out my answer at Call a parent class&#39;s method from child class in Python?.

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

More Related questions