Python Inheritance

Inheritance is a fundamental concept in object-oriented programming where a new class (derived class or child class) is created from an existing class (base class or parent class). The derived class inherits the attributes and methods of the base class and can add its own specific attributes and methods.

Example 1: Simple Inheritance


    class Animal:
      def __init__(self, name):
        self.name = name
    
      def speak(self):
        print("Generic animal sound")
    
    class Dog(Animal):  # Dog inherits from Animal
      def __init__(self, name, breed):
        super().__init__(name)  # Call the constructor of the parent class
        self.breed = breed
    
      def speak(self):
        print("Woof!")
    
    
    my_dog = Dog("Buddy", "Golden Retriever")
    print(my_dog.name)  # Output: Buddy
    print(my_dog.breed)  # Output: Golden Retriever
    my_dog.speak()  # Output: Woof!
    
    my_animal = Animal("Generic Animal")
    my_animal.speak() # Output: Generic animal sound
        

Here, Dog inherits from Animal. Dog gains the name attribute and the speak method from Animal. Crucially, `super().__init__(name)` calls the parent class's constructor to initialize the inherited attributes.

Example 2: Overriding Methods


    class Bird(Animal):
        def speak(self):
            print("Chirp!")
    
    bird = Bird("Tweety")
    bird.speak()  # Output: Chirp!
        

The speak method in Bird overrides the one in Animal.

Example 3: Multiple Inheritance (Illustrative)


    #Illustrative example of multiple inheritance
    class Flyable:
      def fly(self):
        print("I can fly!")
    
    
    class Dragon(Animal, Flyable):
      def __init__(self, name, color):
        super().__init__(name)
        self.color = color
    
    
    # Demonstrating multiple inheritance
    dragon = Dragon("Ignis", "Red")
    dragon.speak() #Output: Generic animal sound
    dragon.fly() #Output: I can fly!
        

This demonstrates a situation where `Dragon` inherits from both `Animal` and `Flyable`. Note, multiple inheritance can sometimes lead to complex behavior; be mindful of how methods might be resolved (in this instance, it is straightforward because `fly()` is only in one parent).

Important Concepts

  • Base Class (Parent Class): The class being inherited from.
  • Derived Class (Child Class): The class inheriting from another class.
  • `super()`: Used to call the constructor of the parent class.
  • Method Overriding: Redefining a method in the derived class to change its behavior.