Python method overload & override

Prerequisite

what is method overloading?

Method overloading simply means that a "function/method" with same "name" behaves differently based on the number of parameters or their data types.

Note: Python does not support the same function/method to defined multiple times by default.

function overloading

Let's take a simple function named add which adds numbers if we pass int and concatenates if we pass strings.

we can use the conditionals to solve it.

def add(x, y):
    if isinstance(x, int) and isinstance(y, int):
        return x + y
    else:
        return f'{x}{y}'

# pass integers
print(add(1,2))
# output: 3
# pass strings
print(add("1","2"))
# output: 12

Note: Keep it simple, you don't want to copy the implementation from other languages. i.e java, c++. Because, construction of the language is different from one another.

method overloading

Just like for functions, it's not possible to use the same method name for different parameters. For this case also, we use conditionals to get the desired output.

Let's look at an example

class Package:
    def __init__(self, product):
        self.product = product

    def pack_product(self, is_gift=None):
        if is_gift:
            print(f"Your {self.product} is packed with special care.")
        else:
            print(f"Your {self.product} is packed.")

package = Package("Mobile")
package.pack_product()
# output: Your Mobile is packed.
package.pack_product(True)
# output: Your Mobile is packed with special care.

Just like above, we can implement the method overload behaviour.

method overriding

Method overriding allows the child/dereived class to define same method name as parent/base class and can replace/modify the inherited behaviour of parent/base class.

Let's look at an example

class Rectangle:
    def __init__(self, length, breadth):
        self.length = length
        self.breadth = breadth

    def area(self):
        return self.length * self.breadth

class Square(Rectangle):
    def __init__(self, side):
        super().__init__(side, side)

rect = Rectange(10, 20)
print(rect.area())
# output: 200
square = Square(10)
print(square.area())
# output: 100
  • If we look at above code we have overridden parent class Rectangle init method in the chile class Square
  • Rectangle init method take two arguments where as child class Square take only one argument.
  • so, by overriding the __init__ method we changed the behaviour of the child class.

Note: Do not override if you didn't use the parent class method functionality.