Back to course

Inheritance 2: Overriding and the `super()` Function

Python Programming: The 0 to Hero Bootcamp

Overriding and super()

Method Overriding

If a child class defines a method that has the exact same name and signature as a method in its parent class, the child's method will be executed instead. This is called method overriding.

In the previous example, Dog and Cat override the generic Animal.speak() method.

The super() Function

Often, a subclass needs to run the parent class's version of a method (especially __init__) before or after adding its own specialized code. super() gives you access to the parent class's methods.

python class Person: def init(self, name, age): self.name = name self.age = age print("Person initialized.")

class Employee(Person): def init(self, name, age, employee_id):

    # 1. Call the parent's constructor using super()
    # This handles initialization of 'name' and 'age'
    super().__init__(name, age)
    
    # 2. Add specific attributes for the subclass
    self.employee_id = employee_id
    print("Employee initialized.")
    
def get_info(self):
    return f"{self.name} ({self.age}), ID: {self.employee_id}"

manager = Employee('Alice', 45, 'E450') print(manager.get_info())