Interview Questions, Answers and Tutorials

Method overriding and method overloading

Method overriding and method overloading

Hello young coder! Today, we’re going to talk about two cool tricks in Python: method overriding and method overloading. Don’t worry, I’ll explain everything in a way that’s easy to understand, and we’ll have some fun with code along the way!

Method Overriding

Imagine you have a magic spell book. In this book, there’s a spell for summoning a pet. But you can change this spell to summon different pets if you want. Method overriding is like changing that spell.

Example:

Let’s say we have a class called ‘Animalwith a method 'make_sound‘. Then, we have another class ‘Dogthat changes (overrides) the ‘make_sound‘ method.

class Animal:
    def make_sound(self):
        return "Some generic animal sound"

class Dog(Animal):
    def make_sound(self):
        return "Woof! Woof!"

# Let's see how it works
generic_animal = Animal()
print(generic_animal.make_sound())  # Output: Some generic animal sound

dog = Dog()
print(dog.make_sound())  # Output: Woof! Woof!

In this example, the ‘Dogclass overrides the ‘make_sound‘ method from the ‘Animalclass. So, when we call ‘make_sound‘ on a ‘Dogobject, it says “Woof! Woof!” instead of “Some generic animal sound”.

Method Overloading

Now, imagine you have a toy robot that can respond to different commands. You can tell it to “move” with one word or give it more detailed instructions like “move forward”. Method overloading is like giving the robot these different commands.

However, in Python, true method overloading (like in some other languages) doesn’t exist. But we can achieve a similar effect by using default values or by checking the number or type of arguments inside a method.

Example:

Let’s create a class ‘Robotwith a method ‘movethat behaves differently based on the arguments.

class Robot:
    def move(self, direction=None, steps=1):
        if direction and steps:
            return f"Moving {direction} for {steps} steps"
        elif direction:
            return f"Moving {direction}"
        else:
            return "Standing still"

# Let's see how it works
robot = Robot()
print(robot.move())  # Output: Standing still
print(robot.move("forward"))  # Output: Moving forward
print(robot.move("left", 3))  # Output: Moving left for 3 steps

In this example, the ‘movemethod in the ‘Robotclass changes its behavior based on the arguments it receives. This is how we can mimic method overloading in Python.

Practice Questions

Now it’s your turn to practice! Here are some questions for you to try:

Question 1:

Create a class ‘Vehiclewith a method ‘start_engine‘. Then create two subclasses, ‘Carand ‘Bike‘, that override the ‘start_engine‘ method to print different messages.

Solution:

class Vehicle:
    def start_engine(self):
        return "Engine starting..."

class Car(Vehicle):
    def start_engine(self):
        return "Car engine starting... Vroom Vroom!"

class Bike(Vehicle):
    def start_engine(self):
        return "Bike engine starting... Brrrr!"

# Testing
car = Car()
print(car.start_engine())  # Output: Car engine starting... Vroom Vroom!

bike = Bike()
print(bike.start_engine())  # Output: Bike engine starting... Brrrr!




Question 2:

Create a class ‘Calculatorwith a method add that can ‘add’ two or three numbers based on the input.

Solution:

class Calculator:
    def add(self, a, b, c=None):
        if c is not None:
            return a + b + c
        else:
            return a + b

# Testing
calc = Calculator()
print(calc.add(2, 3))  # Output: 5
print(calc.add(2, 3, 4))  # Output: 9




Summary

  • Method Overriding is when a subclass changes a method from its parent class.
  • Method Overloading (in a Pythonic way) is when a method can do different things based on the arguments it receives.

By practicing these concepts, you’ll become a better programmer and be able to make your Python programs more flexible and powerful. Happy coding!