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.

Note

Objects in Python are instances of class in Python.

Objects in Python are instances of class in Python.

Adding numbers using Objects

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

Python program to add numbers using Objects

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

The output of the above program is:

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 »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.