8.4 Inheritance

8.4 Inheritance

Learning inheritance to create class hierarchies, reuse code, and override methods.

Inheritance is one of the pillars of OOP. It allows a new class (called a child class, subclass, or derived class) to inherit the attributes and methods of an existing class (called a parent class, superclass, or base class). This promotes an "is-a" logic, for example, "a Dog is an Animal." The child class can reuse the parent's code and also add its own unique attributes and methods, or override the inherited ones.

Override and super()

When a child class defines a method with the same name as a method in its parent class, we say it **overrides** the parent method. To call the parent class's method from within the child (e.g., to extend its functionality rather than completely replacing it), we use the `super()` function.
class Animal: # Parent class
    def __init__(self, name):
        self.name = name
    def make_sound(self):
        return "Generic animal sound"

class Dog(Animal): # Child class
    def make_sound(self): # Method override
        return "Woof! Woof!"

my_dog = Dog("Buddy")
print(f"{my_dog.name} says: {my_dog.make_sound()}")

Practical Exercises

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.