Python Inheritance
Inheritance Fundamentals
Inheritance allows a class (child class) to reuse attributes and methods from another class (parent class). This reduces duplication and models real-world relationships.
Example
# Basic inheritance example
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
return "Some generic animal sound"
def __str__(self):
return f"{self.name} ({self.species})"
class Dog(Animal): # Dog inherits from Animal
def __init__(self, name, breed):
super().__init__(name, "Canine") # Call parent constructor
self.breed = breed
# Method overriding
def make_sound(self):
return "Woof!"
# Method unique to Dog
def fetch(self):
return f"{self.name} is fetching the ball!"
# Creating objects
animal = Animal("Generic", "Animal")
dog = Dog("Buddy", "Golden Retriever")
print(animal)
print(dog)
print(animal.make_sound())
print(dog.make_sound())
print(dog.fetch())
Output
Generic (Animal) Buddy (Canine) Some generic animal sound Woof! Buddy is fetching the ball!
Types of Inheritance
Type | Description | Example |
---|---|---|
Single Inheritance | Child inherits from one parent | class Child(Parent): |
Multiple Inheritance | Child inherits from more than one parent | class Child(Parent1, Parent2): |
Multilevel Inheritance | Child inherits from a parent that itself inherits from another class | class Child(Parent): class Parent(Grandparent): |
Hierarchical Inheritance | Multiple children inherit from the same parent | class Child1(Parent): class Child2(Parent): |
Hybrid Inheritance | Mix of multiple inheritance types | Complex class structure |
Multiple Inheritance
Python supports multiple inheritance, where a class can extend more than one parent class. Method Resolution Order (MRO) determines the search path for methods.
Example
# Multiple inheritance example
class Flyable:
def fly(self):
return "Flying high!"
class Swimmable:
def swim(self):
return "Swimming deep!"
class Duck(Flyable, Swimmable):
def __init__(self, name):
self.name = name
def quack(self):
return "Quack!"
duck = Duck("Donald")
print(duck.quack())
print(duck.fly())
print(duck.swim())
# Method Resolution Order (MRO)
print("MRO:", Duck.__mro__)
Output
Quack! Flying high! Swimming deep! MRO: (<class '__main__.Duck'>, <class '__main__.Flyable'>, <class '__main__.Swimmable'>, <class 'object'>)
Method Overriding and super()
Child classes can override parent methods. The `super()` function lets child methods call the parent’s version of a method to extend rather than replace it.
Example
# Method overriding and super()
class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
return "Engine started"
def get_info(self):
return f"{self.brand} {self.model}"
class Car(Vehicle):
def __init__(self, brand, model, doors):
super().__init__(brand, model)
self.doors = doors
def start_engine(self): # Override
base_result = super().start_engine()
return f"{base_result} - Car ready to drive!"
def get_info(self): # Extend
base_info = super().get_info()
return f"{base_info} with {self.doors} doors"
car = Car("Toyota", "Camry", 4)
print(car.get_info())
print(car.start_engine())
Output
Toyota Camry with 4 doors Engine started - Car ready to drive!