[ACCEPTED]-how to refer to a parent method in python?-polymorphism
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()
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.
Why not keep it simple?
class B(A):
def f(self, num):
return 7 * A.f(self, num)
0
class B(A):
def f(self, num):
return 7 * super(B, self).f(num)
0
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)
Check out my answer at Call a parent class'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
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.