Here, we will add numbers created by two objects in Python.
Problem Description: We have used objects consisting of two variables and then added the values of the object.
Objects in Python are instances of class in Python.
Program to add numbers using Objects in Python
class TwoNum: def getValues(self): self.__x = int(input("Enter x : ")) self.__y = int(input("Enter y : ")) def printValues(self): print(self.__x,self.__y, "Sum = " , (self.__x + self.__y) ) def addObjectValues(self,T): R = TwoNum() R.__x = self.__x+T.__x R.__y = self.__y+T.__y return R print("For Object 1 : ") obj1 = TwoNum() obj1.getValues() print("For Object 2 : ") obj2 = TwoNum() obj2.getValues() sumObj = obj1.addObjectValues(obj2) print("Object 1 :",end=" ") obj1.printValues() print("Object 2 :", end = " ") obj2.printValues() print("Sum Object :", end = " ") sumObj.printValues()
Output:
For Object 1 : Enter x : 43 Enter y : 76 For Object 2 : Enter x : 12 Enter y : 89 Object 1 : 43 76 Sum = 119 Object 2 : 12 89 Sum = 101 Sum Object : 55 165 Sum = 220
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
Program to add numbers using Objects in Python
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer