Python program to pass objects as arguments and return objects from function

Here, we will write a program in Python where we will pass an object as argument to a method and then return another object as result from the method.
Submitted by Shivang Yadav, on March 19, 2021

Class in python are blueprints of the object using which objects are created.

Objects are instances of class in python which have fields and method i.e., values and related functions.

Python allows its programmers to pass objects to method. And also return objects from a method. Here is a program to illustrate this,

Program to pass objects as argument and return objects from function

class TwoNum:
    def GetNum(self):
        self.__x = int(input("Enter value of x : "))
        self.__y = int(input("Enter value of y : "))

    def PutNum(self):
        print("value of x = ", self.__x,"value of y = ", self.__y, )

    def Add(self,T):
        R=TwoNum()
        R.__x=self.__x+T.__x
        R.__y=self.__y+T.__y
        return R

obj1 = TwoNum()
obj2 = TwoNum()
print("Enter values of object 1 ")
obj1.GetNum()
print("Enter values of object 2 ")
obj2.GetNum()
obj3 = obj1.Add(obj2)
print("Values of object 1 ")
obj1.PutNum()
print("Values of object 2 ")
obj2.PutNum()
print("Values of object 3 (sum object) ")
obj3.PutNum()

Output

Enter values of object 1 
Enter value of x : 43
Enter value of y : 65
Enter values of object 2 
Enter value of x : 34
Enter value of y : 65
Values of object 1 
value of x =  43 value of y =  65
Values of object 2 
value of x =  34 value of y =  65
Values of object 3 (sum object) 
value of x =  77 value of y =  130

Program to pass objects as argument and return objects from operator function

class TwoNum:

    def GetNum(self):
        self.__x = int(input("Enter value of x : "))
        self.__y = int(input("Enter value of y : "))

    def PutNum(self):
        print("value of x = ", self.__x,"value of y = ", self.__y, )

    def __add__(self, T):
        R=TwoNum()
        R.__x=self.__x+T.__x
        R.__y=self.__y+T.__y
        return R

obj1 = TwoNum()
obj2 = TwoNum()
print("Enter values of object 1 ")
obj1.GetNum()
print("Enter values of object 2 ")
obj2.GetNum()
obj3 = obj1 + obj2
print("Values of object 1 ")
obj1.PutNum()
print("Values of object 2 ")
obj2.PutNum()
print("Values of object 3 (sum object) ")
obj3.PutNum()

Output

Enter values of object 1 
Enter value of x : 43
Enter value of y : 65
Enter values of object 2 
Enter value of x : 234
Enter value of y : 56
Values of object 1 
value of x =  43 value of y =  65
Values of object 2 
value of x =  234 value of y =  56
Values of object 3 (sum object) 
value of x =  277 value of y =  121

Python class & object programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.