Python Create a Class to Implement Addition, Subtraction, Multiplication and Division
We will create a class named Calculator that will contain four methods:add、subtract、multiply and divide, used respectively for addition, subtraction, multiplication and division.
Example
class
Calculator:
def
init
(
self
,
num1
,
num2
)
:
self
.
num1
=
num1
self
.
num2
=
num2
def
add
(
self
)
:
return
self
.
num1
self
.
num2
def
subtract
(
self
)
:
return
self
.
num1
self
.
num2
def
multiply
(
self
)
:
return
self
.
num1
self
.
num2
def
divide
(
self
)
:
if
self
.
num2
==
0
:
return
"Error: Division by zero is not allowed."
return
self
.
num1
/
self
.
num2
Example usage
calc
=
Calculator
(
10
,
5
)
(
"Addition:"
,
calc.
add
(
)
)
(
"Subtraction:"
,
calc.
subtract
(
)
)
(
"Multiplication:"
,
calc.
multiply
(
)
)
(
"Division:"
,
calc.
divide
(
)
)
Code analysis:
__init__The method is the class constructor, used to initialize an instance of the class. It takes two parametersnum1andnum2and assigns them to the instance variablesself.num1andself.num2。addmethod returnsself.num1andself.num2's sum.subtractmethod returnsself.num1andself.num2's difference.multiplymethod returnsself.num1andself.num2's product.divideThe method first checks whetherself.num2is zero. If it is zero, it returns an error message; otherwise it returnsself.num1divided byself.num2's result.
Output result:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Python3 Examples