free geoip
5

Python Method Overriding Practice in OOP

In object-oriented programming (OOP), method overriding is one of the most powerful concepts that allows developers to redefine methods in…

In object-oriented programming (OOP), method overriding is one of the most powerful concepts that allows developers to redefine methods in child classes that were already defined in their parent classes. In this Python method overriding practice, you will learn how overriding works, why it is used, and how to implement it effectively with practical examples and exercises.

Python Method Overriding Practice

What is Method Overriding?

Method overriding happens when a subclass (child class) defines a method that already exists in its superclass (parent class), but provides its own implementation. The purpose is to change or extend the behavior of the inherited method to suit the child class’s needs.

In simple terms, method overriding allows us to “replace or modify” the functionality that a child class inherits from its parent class.

Basic Syntax

class Parent:
    def show(self):
        print("This is the parent class method")

class Child(Parent):
    def show(self):
        print("This is the child class method")

# Creating objects
p = Parent()
c = Child()

p.show()  # Output: This is the parent class method
c.show()  # Output: This is the child class method

In this example, the Child class overrides the show() method of the Parent class. When we call show() using the child object, the overridden version is executed.

Why Use Method Overriding in Python?

There are several reasons to use method overriding in Python OOP design:

  • To modify behavior: When you want the subclass to behave differently from the parent class.
  • To enhance functionality: When you want to extend what the parent method does, not completely replace it.
  • To maintain flexibility: It allows polymorphism, where the same method name can work differently based on the object type.

Using super() to Call Parent Method

Sometimes, you may want to override a method but still use the parent class’s functionality as part of the child class’s method. You can do this with the super() function.

class Animal:
    def sound(self):
        print("Animal makes a sound")

class Dog(Animal):
    def sound(self):
        super().sound()  # Call parent method
        print("Dog barks")

d = Dog()
d.sound()

Output:

Animal makes a sound
Dog barks

Here, the Dog class overrides the sound() method but still calls the parent’s sound() method using super(). This approach is useful for extending behavior instead of replacing it completely.

Polymorphism and Method Overriding

Method overriding plays an essential role in achieving polymorphism in Python. Polymorphism allows different classes to use the same method name but execute different actions.

class Bird:
    def fly(self):
        print("Birds can fly")

class Penguin(Bird):
    def fly(self):
        print("Penguins cannot fly")

class Eagle(Bird):
    def fly(self):
        print("Eagles fly high in the sky")

def show_fly(thing):
    thing.fly()

b = Bird()
p = Penguin()
e = Eagle()

show_fly(b)  # Birds can fly
show_fly(p)  # Penguins cannot fly
show_fly(e)  # Eagles fly high in the sky

This example demonstrates polymorphism through method overriding. The function show_fly() calls the same fly() method, but the behavior changes depending on the object passed as an argument.

Real-World Example: Bank Account System

Let’s build a more realistic example that shows the practical use of method overriding — a bank account system with different account types.

class BankAccount:
    def __init__(self, balance):
        self.balance = balance

    def withdraw(self, amount):
        if amount > self.balance:
            print("Insufficient funds!")
        else:
            self.balance -= amount
            print(f"Withdrawal successful! Remaining balance: {self.balance}")

class SavingsAccount(BankAccount):
    def withdraw(self, amount):
        if amount > self.balance:
            print("Cannot withdraw more than the balance in savings account!")
        else:
            self.balance -= amount
            print(f"Savings withdrawal successful! New balance: {self.balance}")

class CurrentAccount(BankAccount):
    def withdraw(self, amount):
        # Overriding to allow overdraft up to 1000
        if amount > self.balance + 1000:
            print("Overdraft limit exceeded!")
        else:
            self.balance -= amount
            print(f"Withdrawal successful (with overdraft). New balance: {self.balance}")

# Test
savings = SavingsAccount(2000)
current = CurrentAccount(1000)

savings.withdraw(2500)
current.withdraw(1800)

Output:

Cannot withdraw more than the balance in savings account!
Withdrawal successful (with overdraft). New balance: -800

In this real-world example, both SavingsAccount and CurrentAccount override the withdraw() method from BankAccount but with different behaviors according to their rules. This demonstrates how method overriding helps model real-world differences in class behavior.

Practice Exercise: Try It Yourself

Here’s a simple exercise to practice method overriding in Python:

  1. Create a parent class called Employee with a method get_bonus() that returns 5% of the salary.
  2. Create a subclass Manager that overrides get_bonus() to return 10% of the salary.
  3. Create another subclass Intern that overrides get_bonus() to return 2% of the salary.
  4. Instantiate each class and print their bonus values.

Example Solution:

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def get_bonus(self):
        return self.salary * 0.05

class Manager(Employee):
    def get_bonus(self):
        return self.salary * 0.10

class Intern(Employee):
    def get_bonus(self):
        return self.salary * 0.02

employees = [
    Employee("John", 5000),
    Manager("Alice", 8000),
    Intern("Bob", 3000)
]

for emp in employees:
    print(f"{emp.name} gets bonus: ${emp.get_bonus()}")

Output:

John gets bonus: $250.0
Alice gets bonus: $800.0
Bob gets bonus: $60.0

This exercise helps you understand how method overriding can create flexible and specialized behaviors in subclasses.

Key Takeaways

  • Method overriding allows a subclass to redefine methods from its parent class.
  • Use super() to call the parent version of the overridden method.
  • It’s essential for achieving polymorphism in OOP.
  • Common use cases include customizing or extending base class behavior.

Conclusion

By practicing method overriding in Python, you can write more flexible, reusable, and organized code using object-oriented principles. Whether you are building small projects or large systems, understanding this concept helps in designing classes that can be easily extended and maintained. Continue experimenting with overriding and explore more OOP features like multiple inheritance, encapsulation, and abstract classes to master Python’s OOP system.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *