Overriding Methods & Overloading Operators

Overriding Method:

Method overriding is a concept of object oriented programming that allows us to change the implementation of a function in the child class that is defined in the parent class. It is the ability of a child class to change the implementation of any method which is already provided by one of its parent class(ancestors).

Example 1:

#!/usr/bin/python3
class Parent:        # define parent class
   def myMethod(self):
      print ('Calling parent method')
 
class Child(Parent): # define child class
   def myMethod(self):
      print ('Calling child method')
 
c = Child()          # instance of child
c.myMethod()         # child calls overridden method

Output:

Calling child method

Example 2:

class Rectangle():
	def __init__(self,length,breadth):
		self.length = length
		self.breadth = breadth
	def getArea(self):
		print(self.length*self.breadth," is area of rectangle")
class Square(Rectangle):
	def __init__(self,side):
		self.side = side
		Rectangle.__init__(self,side,side)
	def getArea(self):
		print (self.side*self.side," is area of square")
s = Square(4)
r = Rectangle(2,4)
s.getArea()
r.getArea()

16 is area of square

8 is area of rectangle

Overloading:

  • In Python you can define a method in such a way that there are multiple ways to call it.

  • Given a single method or function, we can specify the number of parameters ourself.

  • Depending on the function definition, it can be called with zero, one, two or more parameters.

  • This is known as method overloading. Not all programming languages support method overloading, but Python does.

Example 3:

#!/usr/bin/env python

class Human:

    def sayHello(self, name=None):
    
        if name is not None:
            print('Hello ' + name)
        else:
            print('Hello ')
        

# Create instance
obj = Human()
    
# Call the method
obj.sayHello()
    
# Call the method with a parameter
obj.sayHello('Guido')

Output:

Hello

Hello Guido

Last updated