Method Overriding in Python


 Method Overriding

     Method overriding is a type of polymorphism in which a child class which is extending the parent class can provide different definition to any function in the parent class as per its own requirements.
Method overriding means a function with same name and signature in both classes parent class and child class.

Example

Imaging a situation in which we have a different class for shapes like square, triangle etc. Which serves as a resource to calculate the area of that shape. Each shape has a different number of dimensions which are used to calculate the area of the respective shape.
Now one approach is to define different functions with different names to calculate the area of the given shapes.

class Square:

        side=5

        def calculate_area_sq(self):

                return self.side*self.side

class Triangle:

        base=5

        height=4

        def calculate_area_tri(self):

                return 0.5*self.base*self.height

sq=Square()

tri=Triangle()

print("Area of square", sq.calculate_area_sq())

print("area of Triangle", tri.calculate_area_tri())

 The problem with this approach is that the developer has to remember the name of each function separately. In a much larger program, it is very difficult to memorize the name of the functions for every small operations. Here comes the role of method overriding.

Now lets change the name of the functions to calculate the area and given them both same name calculate_area() while keeping the function separately in both the classes with different definitions. In this case the type of object will help in resolving the call to the function.

The program below shows the implementation of this type of polymorphism with class methods.

Example

class Square:

        side=5

        def calculate_area(self):

                return self.side*self.side

class Triangle:

        base=5

        height=4

        def calculate_area(self):

                return 0.5*self.base*self.height

sq=Square()

tri=Triangle()

print("Area of square", sq.calculate_area())

print("area of Triangle", tri.calculate_area())

As you can see in this implementation of both classes means Square as well as Triangle has the function with same name calculate_area(), but due to different objects its call get resolved correctly, that is when the function is called using the object sq then the function of class square is called and when its called using the object tri then the function of class Triangle is called.

Output

Area of square 25

area of Triangle 10.0




        

No comments:

Post a Comment