Python Forum

Full Version: How to call base class function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
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.