Search This Blog

Inheritance in Python

 

Inheritance in Python

Inheritance is one of the core concepts in Object-Oriented Programming (OOP). It allows a class (called a subclass or derived class) to inherit attributes and methods from another class (called a base class or parent class). This enables code reuse, allows for hierarchical class relationships, and promotes a more organized structure in large software projects.


1. Basic Concept of Inheritance

When a class inherits from another class, the subclass automatically inherits all the attributes and methods of the parent class, and it can also define its own attributes and methods, or override the inherited ones.

Syntax:

class ParentClass:
    # Parent class code
    pass

class ChildClass(ParentClass):
    # Child class code
    pass

In the above syntax:

  • ParentClass is the base class, and ChildClass is the subclass.
  • The subclass inherits all the properties (methods and attributes) of the parent class.

2. Example of Inheritance

Here’s a basic example of inheritance where a child class inherits from a parent class.

# Parent class (Base Class)
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        print(f"{self.name} makes a sound.")
    
# Child class (Derived Class)
class Dog(Animal):
    def __init__(self, name, breed):
        # Calling the parent class's constructor
        super().__init__(name)
        self.breed = breed
    
    def speak(self):
        # Overriding the parent class method
        print(f"{self.name} barks.")

# Creating an object of the child class
dog1 = Dog("Buddy", "Golden Retriever")

# Calling the inherited method
dog1.speak()  # Output: Buddy barks.

In this example:

  • The Dog class inherits from the Animal class.
  • The Dog class uses the super() function to call the constructor of the Animal class to initialize the name attribute.
  • The speak method is overridden in the Dog class to provide specific behavior for dogs.

3. Types of Inheritance

Python supports different types of inheritance:

1. Single Inheritance

Single inheritance occurs when a subclass inherits from a single parent class.

Example:

class Animal:
    def speak(self):
        print("Animal makes a sound.")

class Dog(Animal):
    def speak(self):
        print("Dog barks.")

# Create an object of Dog
dog = Dog()
dog.speak()  # Output: Dog barks.

2. Multiple Inheritance

Multiple inheritance occurs when a subclass inherits from more than one parent class. In Python, a class can inherit from multiple parent classes.

Example:

class Animal:
    def speak(self):
        print("Animal makes a sound.")

class Mammal:
    def has_fur(self):
        print("Mammals have fur.")

class Dog(Animal, Mammal):
    def speak(self):
        print("Dog barks.")

# Create an object of Dog
dog = Dog()
dog.speak()      # Output: Dog barks.
dog.has_fur()    # Output: Mammals have fur.

In this example:

  • Dog inherits from both Animal and Mammal.
  • The Dog class has access to methods from both the Animal and Mammal classes.

3. Multilevel Inheritance

Multilevel inheritance occurs when a class inherits from a class, which is itself derived from another class.

Example:

class Animal:
    def speak(self):
        print("Animal makes a sound.")

class Mammal(Animal):
    def has_fur(self):
        print("Mammals have fur.")

class Dog(Mammal):
    def speak(self):
        print("Dog barks.")

# Create an object of Dog
dog = Dog()
dog.speak()      # Output: Dog barks.
dog.has_fur()    # Output: Mammals have fur.

In this example:

  • Dog inherits from Mammal, which in turn inherits from Animal.

4. Hierarchical Inheritance

Hierarchical inheritance occurs when multiple subclasses inherit from a single parent class.

Example:

class Animal:
    def speak(self):
        print("Animal makes a sound.")

class Dog(Animal):
    def speak(self):
        print("Dog barks.")

class Cat(Animal):
    def speak(self):
        print("Cat meows.")

# Create objects of Dog and Cat
dog = Dog()
cat = Cat()

dog.speak()  # Output: Dog barks.
cat.speak()  # Output: Cat meows.

In this example:

  • Both Dog and Cat inherit from the Animal class.

5. Hybrid Inheritance

Hybrid inheritance is a combination of two or more of the inheritance types mentioned above.

Example:

class Animal:
    def speak(self):
        print("Animal makes a sound.")

class Mammal(Animal):
    def has_fur(self):
        print("Mammals have fur.")

class Reptile(Animal):
    def lays_eggs(self):
        print("Reptiles lay eggs.")

class Platypus(Mammal, Reptile):
    def speak(self):
        print("Platypus makes a unique sound.")

# Create an object of Platypus
platypus = Platypus()
platypus.speak()    # Output: Platypus makes a unique sound.
platypus.has_fur()  # Output: Mammals have fur.
platypus.lays_eggs()# Output: Reptiles lay eggs.

Here, Platypus inherits from both Mammal and Reptile, which are both derived from Animal.


4. The super() Function

The super() function is used to call a method from the parent class. This is particularly useful when you want to call the constructor or methods of the parent class in the child class.

Example:

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

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

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)  # Calling the parent class constructor
        self.breed = breed

    def speak(self):
        print(f"{self.name} barks.")

dog = Dog("Buddy", "Golden Retriever")
dog.speak()  # Output: Buddy barks.

In this example:

  • super().__init__(name) calls the __init__ method of the parent class Animal to initialize the name attribute.

5. Overriding Methods

In inheritance, a child class can override the methods of the parent class. This means the child class provides its own implementation of the method.

Example of Method Overriding:

class Animal:
    def speak(self):
        print("Animal makes a sound.")

class Dog(Animal):
    def speak(self):
        print("Dog barks.")

dog = Dog()
dog.speak()  # Output: Dog barks.

In this case, the speak method in the Dog class overrides the speak method in the Animal class.


6. The issubclass() and isinstance() Functions

  • issubclass(): Checks if a class is a subclass of another class.
  • isinstance(): Checks if an object is an instance of a specified class or a subclass of that class.

Example:

class Animal:
    pass

class Dog(Animal):
    pass

# Check if Dog is a subclass of Animal
print(issubclass(Dog, Animal))  # Output: True

# Check if an object is an instance of Dog or Animal
dog = Dog()
print(isinstance(dog, Dog))  # Output: True
print(isinstance(dog, Animal))  # Output: True

7. Summary

  • Inheritance allows classes to reuse the code of other classes, establishing a relationship between parent (base) and child (derived) classes.
  • There are different types of inheritance: Single, Multiple, Multilevel, Hierarchical, and Hybrid.
  • The super() function is used to call methods from a parent class.
  • A child class can override methods of the parent class to provide specific behavior.
  • The issubclass() and isinstance() functions help check class relationships.

Inheritance provides a powerful way to create hierarchical structures and to reuse and extend existing code in a flexible and maintainable way.

Popular Posts