Inheritance is a core principle of Object-Oriented Programming (OOP) that allows a new class (the child class) to acquire the properties (attributes and methods) of an existing class (the parent class). This creates a logical "is-a" relationship (e.g., a Dog is an Animal) and is a powerful tool for code reuse.
1. Single Inheritance
This is the most straightforward type of inheritance. A child class inherits from only one parent class. It gains all the attributes and methods of that single parent.
- Use Case: To create a more specific version of a general class. This is the most common form of inheritance used to model real-world hierarchies.
Python
# --- Single Inheritance Example ---
# Parent Class
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
return f"{self.name} is eating."
# Child Class inherits from the single 'Animal' parent.
class Dog(Animal):
def bark(self):
return "Woof!"
# The Dog object has access to methods from both its own class and its parent's.
my_dog = Dog("Buddy")
print(my_dog.eat()) # Method inherited from Animal
print(my_dog.bark()) # Method from the Dog class
2. Multiple Inheritance
A child class can inherit from more than one parent class. It inherits all attributes and methods from all parent classes listed in its definition.
- Use Case: When a class represents an object that is a combination of several different, often unrelated, things (a mixin pattern). For example, a FlyingCar might inherit from both a Car class and a Plane class.
Python
# --- Multiple Inheritance Example ---
class Swimmer:
def swim(self):
return "I can swim!"
class Flyer:
def fly(self):
return "I can fly!"
# This class inherits from both Swimmer and Flyer.
class Duck(Swimmer, Flyer):
def quack(self):
return "Quack!"
my_duck = Duck()
# The Duck object has access to methods from both parent classes.
print(f"A duck says: {my_duck.swim()} and {my_duck.fly()}")
3. Multilevel Inheritance
This is when a child class becomes a parent class for another child class, creating a chain of inheritance. A class inherits from a derived class, making it the grandchild of the base class.
- Use Case: To model a deep hierarchy of classifications where each level adds more specificity. For example, Organism -> Animal -> Mammal -> Dog.
Python
# --- Multilevel Inheritance Example ---
class Grandparent:
def greet_grandparent(self):
return "Hello from Grandparent"
class Parent(Grandparent): # Inherits from Grandparent
def greet_parent(self):
return "Hello from Parent"
class Child(Parent): # Inherits from Parent
def greet_child(self):
return "Hello from Child"
my_child = Child()
# The Child object has access to methods from all its ancestors in the chain.
print(my_child.greet_grandparent())
print(my_child.greet_parent())
print(my_child.greet_child())
4. Hierarchical Inheritance
This is when multiple child classes all inherit from a single parent class. This is the opposite of multiple inheritance.
- Use Case: The most common structure for modeling "is-a" relationships where you have one general category and several specific types. For example, Dog, Cat, and Fish are all different types of Animal.
Python
# --- Hierarchical Inheritance Example ---
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
return f"{self.name} is eating."
class Dog(Animal):
def bark(self):
return "Woof!"
class Cat(Animal):
def meow(self):
return "Meow!"
# Both Dog and Cat inherit from the same parent, Animal.
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.eat())
print(cat.eat())
Functions Used with Inheritance
Python provides built-in functions to check the relationships between objects and classes.
isinstance()
Checks if an object is an instance of a particular class or any of its parent classes.
Python
dog = Dog("Buddy")
print(f"\nIs dog an instance of Dog? {isinstance(dog, Dog)}") # Output: True
print(f"Is dog an instance of Animal? {isinstance(dog, Animal)}") # Output: True
print(f"Is dog an instance of Cat? {isinstance(dog, Cat)}") # Output: False
issubclass()
Checks if a class is a subclass of (i.e., inherits from) another class.
Python
print(f"\nIs Dog a subclass of Animal? {issubclass(Dog, Animal)}") # Output: True
print(f"Is Animal a subclass of Dog? {issubclass(Animal, Dog)}") # Output: False