Python Define a Class with Multiple Methods, Each Performing a Different Math Operation
We will define a class named MathOperations that contains multiple methods, each performing a different math operation such as addition, subtraction, multiplication, and division.
Example
class
MathOperations:
def
add
(
self
,
a
,
b
)
:
return
a + b
def
subtract
(
self
,
a
,
b
)
:
return
a - b
def
multiply
(
self
,
a
,
b
)
:
return
a * b
def
divide
(
self
,
a
,
b
)
:
if
b
==
0
:
return
"Error: Division by zero is not allowed."
return
a / b
Code analysis:
add(self, a, b): this method takes two parametersaandband returns their sum.subtract(self, a, b): this method takes two parametersaandband returns their difference.multiply(self, a, b): this method takes two parametersaandband returns their product.divide(self, a, b): this method takes two parametersaandband returns their quotient. Ifbis 0, return an error message, because division by zero is not allowed.
Output result:
Example
math_ops
=
MathOperations
(
)
(
math_ops.
add
(
10
,
5
)
)
Output: 15
(
math_ops.
subtract
(
10
,
5
)
)
Output: 5
(
math_ops.
multiply
(
10
,
5
)
)
Output: 50
(
math_ops.
divide
(
10
,
5
)
)
Output: 2.0
(
math_ops.
divide
(
10
,
0
)
)
Python3 Examples