Python inheritance - how to inherit class function?

Learn python inheritance - how to inherit class function? with practical examples, diagrams, and best practices. Covers python, class, inheritance development techniques with visual explanations.

Python Inheritance: Mastering Class Function Overriding and Extension

Hero image for Python inheritance - how to inherit class function?

Explore the fundamentals of inheritance in Python, focusing on how to inherit, override, and extend class functions to build robust and reusable code structures.

Inheritance is a cornerstone of object-oriented programming (OOP) in Python, allowing you to define a new class based on an existing class. This mechanism promotes code reusability and establishes a natural hierarchy between classes. When a class inherits from another, it gains access to all the attributes and methods (functions) of its parent class. This article will guide you through the process of inheriting class functions, understanding method overriding, and extending parent class functionality.

Understanding Basic Inheritance

At its core, inheritance means that a child class (also known as a subclass or derived class) automatically receives the methods and attributes of its parent class (also known as a superclass or base class). This allows you to create specialized versions of existing classes without rewriting common code. The child class can then add its own unique methods or modify inherited ones.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound."

class Dog(Animal):
    pass # Dog inherits everything from Animal

my_dog = Dog("Buddy")
print(my_dog.speak()) # Output: Buddy makes a sound.

A basic example of a Dog class inheriting from an Animal class.

classDiagram
    Animal <|-- Dog
    Animal : +name
    Animal : +speak()
    Dog : +__init__()
    Dog : +bark()

Class diagram illustrating the inheritance relationship between Animal and Dog.

Method Overriding: Customizing Inherited Behavior

One of the most powerful features of inheritance is method overriding. This allows a child class to provide a specific implementation for a method that is already defined in its parent class. When an instance of the child class calls that method, the child's implementation is executed instead of the parent's. This is crucial for tailoring behavior to the specific needs of the subclass.

class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a generic sound."

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

my_cat = Cat("Whiskers")
print(my_cat.speak()) # Output: Whiskers says Meow!

my_animal = Animal("Unknown")
print(my_animal.speak()) # Output: Unknown makes a generic sound.

The Cat class overrides the speak method from Animal.

Extending Parent Functionality with super()

Often, you don't want to completely replace a parent method's functionality but rather extend it. Python's super() function provides a way to call a method from the parent class, even if that method has been overridden in the child class. This is particularly useful in __init__ methods to ensure that the parent class is properly initialized, but it can be used with any method.

class Vehicle:
    def __init__(self, brand, year):
        self.brand = brand
        self.year = year

    def get_info(self):
        return f"Brand: {self.brand}, Year: {self.year}"

class Car(Vehicle):
    def __init__(self, brand, year, model):
        super().__init__(brand, year) # Call parent's __init__
        self.model = model

    def get_info(self):
        # Call parent's get_info and extend it
        parent_info = super().get_info()
        return f"{parent_info}, Model: {self.model}"

my_car = Car("Toyota", 2023, "Camry")
print(my_car.get_info()) # Output: Brand: Toyota, Year: 2023, Model: Camry

Using super() to extend the __init__ and get_info methods.