Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Create a Class to Implement Addition, Subtraction, Multiplication and Division

Python Create a Class to Implement Addition, Subtraction, Multiplication and Division

Document Object Reference Manual Python3 Examples

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

)

print

(

"Addition:"

,

calc.

add

(

)

)

print

(

"Subtraction:"

,

calc.

subtract

(

)

)

print

(

"Multiplication:"

,

calc.

multiply

(

)

)

print

(

"Division:"

,

calc.

divide

(

)

)

Code analysis:

  1. __init__ The method is the class constructor, used to initialize an instance of the class. It takes two parameters num1 and num2and assigns them to the instance variables self.num1 and self.num2。
  2. add method returns self.num1 and self.num2 's sum.
  3. subtract method returns self.num1 and self.num2 's difference.
  4. multiply method returns self.num1 and self.num2 's product.
  5. divide The method first checks whether self.num2 is zero. If it is zero, it returns an error message; otherwise it returns self.num1 divided by self.num2 's result.

Output result:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0

Document Object Reference Manual Python3 Examples