Python Inheritance

In Python, inheritance is a powerful feature of object-oriented programming (OOP) that allows you to create a new class (called the derived class or subclass) based on an existing class (called the base class or superclass). The derived class inherits the attributes and methods of the base class, and you can also add new attributes and methods or modify the inherited ones. Inheritance promotes code reuse and supports the concept of hierarchical relationships between classes.

To define inheritance in Python, you can create a subclass by specifying the base class inside parentheses after the subclass name in the class definition. The syntax for creating a subclass is as follows:

Example
class SubclassName(BaseClassName):
    # Additional attributes and methods specific to the subclass

Here are some key points to understand about inheritance:

  • The derived class inherits all the attributes and methods of the base class. This means that instances of the derived class will have access to the inherited attributes and methods.

  • The derived class can override the methods of the base class by redefining them in the subclass. This is known as method overriding.

  • The derived class can also add new attributes and methods specific to itself.

  • Multiple inheritance is possible, where a subclass can inherit from multiple base classes. In such cases, the class definition would include multiple base classes separated by commas.

Here's an example to illustrate inheritance in Python:

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

    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Woof!")

    def fetch(self):
        print("Fetching...")

# Creating an instance of the base class
animal = Animal("Generic Animal")
animal.speak()  # Output: Animal speaks

# Creating an instance of the derived class
dog = Dog("Buddy")
dog.speak()  # Output: Woof!
dog.fetch()  # Output: Fetching...

In the above code, we have a base class Animal with an __init__() method and a speak() method. The Dog class is derived from the Animal class. It overrides the speak() method and adds a new method called fetch().

When we create an instance of the base class (animal = Animal("Generic Animal")) and call its speak() method, it prints "Animal speaks". Similarly, when we create an instance of the derived class (dog = Dog("Buddy")) and call its speak() method, it prints "Woof!". We can also call the fetch() method, which is specific to the Dog class.

Inheritance allows you to create classes that build upon existing classes, promoting code reuse and making your code more modular and maintainable.