Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to refer to a parent method in python? [duplicate]

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.

like image 942
user1111042 Avatar asked Feb 19 '12 07:02

user1111042


People also ask

What does super () __ Init__ do?

When you initialize a child class in Python, you can call the super(). __init__() method. This initializes the parent class object into the child class. In addition to this, you can add child-specific information to the child object as well.

How do you call parent method from child object?

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.

How do you access the attribute of a parent class in Python?

Accessing Parent Class Functions This is really simple, you just have to call the constructor of parent class inside the constructor of child class and then the object of a child class can access the methods and attributes of the parent class.


2 Answers

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

like image 116
jimifiki Avatar answered Sep 20 '22 03:09

jimifiki


Use super:

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

Or in python 3, it's just:

return 7 * super().f(num) 
like image 39
tzaman Avatar answered Sep 24 '22 03:09

tzaman