Object-Oriented-Python

Mathematical Operations in Python using Object-Oriented Programming in Python

Python is an object-oriented language and a class can have properties and methods. In this post, I will create a simple class having a constructor __init__() and four methods namely mysum(), mymul(), mydiv() and mysub(). Moreover, they compute addition of two numbers, multiplication of two numbers, division of a number by another and subtraction  of a number.

See the code

class Mymath:
def __init__(self, x, y):
           self.x=x
           self.y=y
def mysum(self):
           res=self.x + self.y
           return res
def mymul(self):
           res=self.x * self.y
           return res
def mydiv(self):
           res=self.x / self.y
           return res
def mysub(self):
           res=self.x - self.y
           return res
mm=Mymath(24,6)
sm=mm.mysum()
ml=mm.mymul()
dv=mm.mydiv()
ms=mm.mysub()
print(sm,ml,dv,ms)

 

Object-Oriented-Python

In the above program, a class Mymath is defined having five methods __init__() mysum(), mymul(), mydiv() and mysub(). __init_()   method is invoked when constructor Mymath(24,6) is called. You can observe that __init__() method has three parameters,  self, x and y.  Note that self is not a keyword, you can take any valid identifier in Python, conventionally this identifier is used. self receives object mm created by constructor i.e. Mymath(24,6). Moreover, statements self.x and self.y initialize values of x and y associated with objects mm. Further, functions mysum(), mymul(), mydiv() and mysub() use self.x and self.y and compute summation, multiplication, division and subtraction.

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

©Postnetwork-All rights reserved.