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

Python Define a Class with Multiple Methods, Each Performing a Different Math Operation

Python Define a Class with Multiple Methods, Each Performing a Different Math Operation

Document Object Reference Manual Python3 Examples

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:

Output result:

Example

math_ops

=

MathOperations

(

)

print

(

math_ops.

add

(

10

,

5

)

)

       

Output: 15

print

(

math_ops.

subtract

(

10

,

5

)

)

 

Output: 5

print

(

math_ops.

multiply

(

10

,

5

)

)

 

Output: 50

print

(

math_ops.

divide

(

10

,

5

)

)

   

Output: 2.0

print

(

math_ops.

divide

(

10

,

0

)

)

   

Output: Error: Division by zero is not allowed.

Document Object Reference Manual Python3 Examples