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

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

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

Document Object Reference Manual Python3 Examples

We will write a class named Calculator containing four methods:add(addition),subtract(subtraction),multiply(multiplication) and divide(division). These methods take two numbers as arguments and return the corresponding result.

Example

class

Calculator:

   

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

:

           

raise

ValueError

(

"Cannot divide by zero."

)

       

return

a / b

Code analysis:

Output result:

Example

calc

=

Calculator

(

)

print

(

calc.

add

(

10

,

5

)

)

       

Output: 15

print

(

calc.

subtract

(

10

,

5

)

)

 

Output: 5

print

(

calc.

multiply

(

10

,

5

)

)

 

Output: 50

print

(

calc.

divide

(

10

,

5

)

)

   

Output: 2.0

This class can be used for basic arithmetic, and exception handling makes division safe.

Document Object Reference Manual Python3 Examples