How to call method of another class in your class in Python

In this tutorial, I am gonna show you how to access the method of another class from your class or child class by using dot(.) operator.

Call method from another class in a different class in Python

we can call the method of another class by using their class name and function with dot operator.
for Example:-
if the 1st class name is class A and its method is method_A
and the second class is class B and its method is method_B
then we can call method_A from class B by following way:

class A:
     method_A(self):
      {}
class B:
     method_B(self):
     A.method_A()   (like this ....)
     {}

   
Details:
         A: class name
         .: dot operator
method_A(): method of class A. 

 

now I am gonna create a 1st parent class which has a method name sum which will return the sum of 2 nos.

#create parent class whose method is called by your class 
class parent:
    def sum(self,a,b):
        return a+b

now I am going to create another class from there we will call sum method of a parent class.

class your_class:
    def Fun(self,a,b):
        self.a=a
        self.b=b
        '''
        we can call method of another class
        by using their class name and function with dot operator.
        '''
        x=parent.sum(self,a,b)
        print("sum=",x)

Complete code in a single window:




Python program to call a method from another class

#create parent class whose method is called by your class 
class parent:
    def sum(self,a,b):
        return a+b
class your_class:
    def Fun(self,a,b):
        self.a=a
        self.b=b
        '''
        we can call method of another class
        by using their class name and function with dot operator.
        '''
        x=parent.sum(self,a,b)
        print("sum=",x)
#class object of child class or 
ob=your_class()
x=int(input("enter 1st no."))
y=int(input("enter 2nd no."))
#fuction call of your class
ob.Fun(x,y)

Output:

enter 1st no.6
enter 2nd no.5
sum= 11

You may also read:


Leave a Reply

Your email address will not be published. Required fields are marked *