Q:

Python program to add numbers using Objects

belongs to collection: Python class & object programs

0

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.

All Answers

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

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

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
Multiple Inheritance Example in Python... >>
<< Parameterized Constructor and Destructor Example i...