ADVERTISEMENT
ADVERTISEMENT

Python program to add numbers using Objects

Here, we are going to learn how to add numbers using Objects in Python?
Submitted by Shivang Yadav, on February 16, 2021

Problem statement: 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.

We will create objects of class with two variables x and y. And then added the objects and returned their sum.

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

Python class & object programs »



ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.