Python Inheritance

Python, a language renowned for its simplicity and readability, offers a powerful feature known as inheritance. Inheritance allows a class to inherit attributes and methods from another class, promoting code reuse and the creation of more complex functionality with less code.

1. Create a Parent Class

Inheritance in Python begins with the creation of a parent class. A parent class, or base class, is a class that passes its attributes and methods to a child class. Here’s how to define one:

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

    def make_sound(self):
        print("Some generic sound")

In this example, Animal is a parent class with an attribute species and a method make_sound.

2. Add the init() Function

The __init__() function is a special method in Python. It’s called when an object is created from a class and allows the class to initialize the object’s attributes. In the context of inheritance, we can define it in a child class to extend or modify the functionality of the parent class.

3. Use the super() Function

The super() function is a key part of inheritance in Python. It allows us to call methods from the parent class. This is particularly useful in the __init__() function to ensure the parent class is properly initialized.

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

Here, Dog is a child class that inherits from Animal, and super().__init__(species) ensures the species attribute is set by the parent class’s __init__() method.

4. Add Properties

Properties are special kinds of attributes. They allow you to implement getters, setters, and deleters. This is useful when you need to add validation logic around getting and setting a value.

class Cat(Animal):
    def __init__(self, species, name):
        super().__init__(species)
        self._name = name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, value):
        if not isinstance(value, str):
            raise ValueError("Name must be a string")
        self._name = value

5. Add Methods

Methods define behaviors. In the context of inheritance, child classes can either use methods from the parent class, override them, or introduce new methods.

class Bird(Animal):
    def make_sound(self):
        print("Chirp chirp")

In this example, Bird overrides the make_sound method of the Animal class.

Conclusion

Inheritance is a fundamental aspect of Python that helps in building a modular and efficient codebase. By understanding and utilizing parent and child classes, the __init__() function, the super() function, properties, and methods, developers can create versatile and reusable code structures.

Happy Coding!