Python Forum
How to call base class function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to call base class function
#1
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
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  The function of double underscore back and front in a class function name? Pedroski55 9 619 Feb-19-2024, 03:51 PM
Last Post: deanhystad
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 787 May-02-2023, 08:40 AM
Last Post: Gribouillis
  How to call a class in other class? 3lnyn0 3 923 Oct-24-2022, 09:18 AM
Last Post: GenTorossi
  TimeOut a function in a class ? Armandito 1 1,642 Apr-25-2022, 04:51 PM
Last Post: Gribouillis
  Calling a base class variable from an inherited class CompleteNewb 3 1,673 Jan-20-2022, 04:50 AM
Last Post: CompleteNewb
  Calling a class from a function jc4d 5 1,807 Dec-17-2021, 09:04 PM
Last Post: ndc85430
  a function common to methods of a class Skaperen 7 2,567 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  Tuple generator, and function/class syntax quazirfan 3 3,854 Aug-10-2021, 09:32 AM
Last Post: buran
  Importing issues with base class for inheritance riccardoob 5 4,665 May-19-2021, 05:18 PM
Last Post: snippsat
  how to call an object in another function in Maya bstout 0 2,071 Apr-05-2021, 07:12 PM
Last Post: bstout

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020