Overriding

Method Overriding happens when a child class defines a method with the exact same name as one in its parent class, replacing the parent's version specifically for objects of that child class.

Basic Overriding

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

class Dog(Animal):
    def sound(self):
        print("Bark!")

a = Animal()
d = Dog()

a.sound()   # Some generic animal sound
d.sound()   # Bark! (overridden)

Even though Dog inherits from Animal, calling sound() on a Dog object runs the child class's own version instead of the parent's.

Calling the Parent's Method with super()

Sometimes you want to override a method but still run the parent's original logic as part of it. The super() function lets you do exactly that.

class Employee:
    def details(self):
        print("Generic employee details")

class Manager(Employee):
    def details(self):
        super().details()
        print("Manages a team")

m = Manager()
m.details()
# Generic employee details
# Manages a team
Overriding is a core part of Polymorphism - it's what allows different subclasses to share a common interface (the same method name) while each providing its own specific behavior underneath.

Coming Up Next

Next, you'll learn about Getter and Setter methods - a controlled way to access and update an object's private data.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course