1. Home
  2. Docs
  3. Exercises
  4. Classes and Objects

Classes and Objects

In this section you find Exercises of Class and Objects,
 

Try yourself first before checking the solutions.

 

Exercise 1:
 

Write a simple MyMath class with, instance methods for addition, subtraction, multiplication,
division and power functions.
 
Solution:

 

class MyMath(object):
    
    def add(self,a,b):
        return a + b
    
    def sub(self,a,b):
        return a - b
        
    def mul(self, a, b):
        return a * b
    
    def divide(self, a,b):
        if b :
            return a/b
        else:
            return "can't divide by zero"
        
    def pow(self, a , b):
        return a ** b
    

#sample test

a1 = MyMath()
print(a1.add(3,3))
print(a1.sub(3,5))
print(a1.mul(2,6))
print(a1.divide(2,0))
print(a1.pow(3,3))


output:

6
-2
12
can't divide by zero
27