![]() |
| How to call base class function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to call base class function (/thread-17235.html) |
How to call base class function - kamal_chennai - Apr-03-2019 Hi Team, Please find the below code class A () : def __init__(self,name): self.name = name def fun(self): print("The name is " , self.name) class B(A) : def __init__(self,Location): A.__init__(self,name) self.Location = Location def fun(self): print("The Location is " , self.Location) obj1 = B("Chennai") x = obj1.fun()Class A and Class B contains similar method name "fun"now i have created one instance obj1 = B("Chennai"). Instead of calling the "fun" from class B, i want to call a "fun" from class A. is it possible to call a class A "fun" from created instance. thanks in advance Kamal RE: How to call base class function - ichabod801 - Apr-03-2019 You can use super(B, obj1).fun(). The super function will get a proxy object of the parent class of the specified class as if it was the specified object. Note that you could use A.fun(obj1), which takes the unbound method from the class and supplies obj1 as self. However, super is preferred as it can handle more complicated class structures. In fact, it would be preferred to use super().__init__(name) for line 10 (inside a class method super can figure out for itself the needed class and instance). Of course, that fails because name is not defined in B.__init__, but I figure this is a toy example of a more complicated situation you are asking about. |