Python Inheritance
Learn Python through interactive, bite-sized lessons. Practice with real code challenges and build projects step-by-step.
Start Python Journey →Inheritance is a fundamental concept in object-oriented programming (OOP) that allows classes to inherit attributes and methods from other classes. It promotes code reuse and establishes a hierarchical relationship between classes.
Basic Syntax
In Python, inheritance is implemented using the following syntax:
class ChildClass(ParentClass):
# Child class definition
The child class inherits all attributes and methods from the parent class, also known as the base class or superclass.
Types of Inheritance
- Single Inheritance: A child class inherits from one parent class
- Multiple Inheritance: A child class inherits from multiple parent classes
- Multilevel Inheritance: A child class inherits from a parent class, which in turn inherits from another class
Example: Single Inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
dog = Dog("Buddy")
print(dog.speak()) # Output: Buddy says Woof!
In this example, the Dog class inherits from the Animal class and overrides the speak method.
The super() Function
The super() function allows you to call methods from the parent class. It's particularly useful when you want to extend the functionality of a parent class method:
class Bird(Animal):
def __init__(self, name, wingspan):
super().__init__(name)
self.wingspan = wingspan
def speak(self):
return f"{self.name} chirps!"
parrot = Bird("Polly", 20)
print(parrot.speak()) # Output: Polly chirps!
Method Resolution Order (MRO)
In cases of multiple inheritance, Python uses the C3 linearization algorithm to determine the method resolution order. You can view the MRO using the __mro__ attribute or the mro() method:
print(Bird.__mro__)
# Output: (<class '__main__.Bird'>, <class '__main__.Animal'>, <class 'object'>)
Best Practices
- Use inheritance to model "is-a" relationships
- Favor composition over inheritance for "has-a" relationships
- Keep inheritance hierarchies shallow to maintain code readability
- Use abstract base classes to define interfaces (Python Abstract Classes)
Related Concepts
To fully understand inheritance in Python, it's helpful to explore these related topics:
By mastering inheritance, you'll be able to create more efficient, organized, and reusable code in your Python projects.