Q:

Python program to add objects \'+\' using operator

belongs to collection: Python class & object programs

0

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
    • MethodgetValue() -> get input values from the user.
    • MethodprintValues() -> prints values and their sum.
    • Operator__add__() -> adds objects.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python class & object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to see the working of filter() meth... >>
<< Multilevel Inheritance Example in Python...