Home »
Python »
Python programs
Python program to add objects '+' using operator
Here, we are going to learn how to add objects '+' using operator in Python?
Submitted by Shivang Yadav, on February 16, 2021
Problem statement: Program to add objects using '+' operator in Python.
Problem description: we will add objects using the '+' operator in Python.
In the program, we will create three objects and then add them using the '+' operator. And return the result of addition. Each object will contain two variables that will be added to the variables of other objects on calling the addition operator.
Class and methods used:
-
Class : TwoNum
- Method: getValue() -> get input values from the user.
- Method: printValues() -> prints values and their sum.
- Operator: __add__() -> adds objects.
Program to illustrate the working of our solution
class TwoNum:
def getValue(self):
self.__x=int(input("Enter X: "))
self.__y=int(input("Enter y: "))
def printValue(self):
print(self.__x,self.__y, "sum = ", (self.__x + 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()
obj3 = TwoNum()
print("Object 1 : ")
obj1.getValue()
print("Object 2 : ")
obj2.getValue()
print("Object 3 : ")
obj3.getValue()
sumObj = obj1+obj2+obj3
print("Values : ")
print("Object 1 :", end = " ")
obj1.printValue()
print("Object 2 :", end = " ")
obj2.printValue()
print("Object 3 :", end = " ")
obj3.printValue()
print("Sum object :", end = " ")
sumObj.printValue()
Output:
Object 1 :
Enter X: 65
Enter y: 76
Object 2 :
Enter X: 34
Enter y: 5
Object 3 :
Enter X: 23
Enter y: 7
Values :
Object 1 : 65 76 sum = 141
Object 2 : 34 5 sum = 39
Object 3 : 23 7 sum = 30
Sum object : 122 88 sum = 210
Python class & object programs »