Python Inheritance Tutorial
Quick Answer
Inheritance explains inheritance is a fundamental concept in object-oriented programming that allows a class to inherit attributes and methods from another class.
Learning Objectives
- Explain the purpose of Inheritance in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Inheritance.
- Apply Inheritance in a simple real-world scenario or practice task.
Introduction to Python Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit attributes and methods from another class.
In Python, inheritance enables code reuse and the creation of hierarchical relationships between classes.
This tutorial will guide you through the basics of inheritance in Python with practical examples and explanations.
Inheritance promotes code reuse and establishes a natural hierarchy.
What is Inheritance?
Inheritance allows a new class, called a child or subclass, to acquire the properties and behaviors of an existing class, called a parent or superclass.
This mechanism helps reduce code duplication and makes programs easier to maintain.
- Child class inherits attributes and methods from the parent class.
- Child class can add new attributes or override existing methods.
- Supports the concept of 'is-a' relationship.
Basic Syntax of Inheritance in Python
To create a subclass in Python, specify the parent class name in parentheses after the subclass name.
The subclass inherits all methods and attributes from the parent class unless overridden.
Example of Simple Inheritance
Here is a basic example demonstrating inheritance in Python.
Overriding Methods
A subclass can provide its own implementation of a method inherited from the parent class. This is called method overriding.
Overriding allows customizing or extending the behavior of the parent class.
- Use the same method name in the subclass.
- Call the parent method using super() if needed.
Using super() Function
The super() function allows you to call methods from the parent class inside the subclass.
It is commonly used to extend the functionality of the parent method rather than completely replacing it.
- Call super().__init__() to invoke the parent class constructor.
- Use super() to access other parent class methods.
Types of Inheritance in Python
Python supports several types of inheritance to model different relationships between classes.
- Single Inheritance: One subclass inherits from one parent class.
- Multiple Inheritance: One subclass inherits from multiple parent classes.
- Multilevel Inheritance: A subclass inherits from a class which is also a subclass.
- Hierarchical Inheritance: Multiple subclasses inherit from one parent class.
- Hybrid Inheritance: Combination of two or more types of inheritance.
| Type | Description | Example |
|---|---|---|
| Single | One subclass inherits from one parent class | class B(A): pass |
| Multiple | One subclass inherits from multiple parent classes | class C(A, B): pass |
| Multilevel | Subclass inherits from a subclass | class C(B): pass where B inherits A |
| Hierarchical | Multiple subclasses inherit from one parent |
Practical Example
This example shows a Dog class inheriting from Animal and overriding the speak method.
The Employee class calls the Person constructor using super() to initialize the name attribute.
Examples
class Animal:
def speak(self):
print('Animal speaks')
class Dog(Animal):
def speak(self):
print('Dog barks')
my_dog = Dog()
my_dog.speak()This example shows a Dog class inheriting from Animal and overriding the speak method.
class Person:
def __init__(self, name):
self.name = name
class Employee(Person):
def __init__(self, name, employee_id):
super().__init__(name)
self.employee_id = employee_id
emp = Employee('Alice', 123)
print(emp.name, emp.employee_id)The Employee class calls the Person constructor using super() to initialize the name attribute.
Best Practices
- Use inheritance to promote code reuse and logical class hierarchies.
- Avoid deep inheritance trees to reduce complexity.
- Use method overriding carefully to maintain expected behavior.
- Use super() to call parent methods and constructors properly.
- Prefer composition over inheritance when appropriate.
Common Mistakes
- Overusing inheritance leading to complicated class hierarchies.
- Not calling super() in overridden constructors causing incomplete initialization.
- Overriding methods without preserving parent behavior when needed.
- Confusing multiple inheritance leading to method resolution order issues.
Hands-on Exercise
Create a Vehicle Inheritance Hierarchy
Define a base class Vehicle with attributes like make and model. Create subclasses Car and Motorcycle that inherit from Vehicle and add specific attributes or methods.
Expected output: Classes Vehicle, Car, and Motorcycle with appropriate attributes and methods demonstrating inheritance.
Hint: Use inheritance syntax and override methods if needed.
Override a Method and Use super()
Create a base class Shape with a method area(). Create a subclass Rectangle that overrides area() and uses super() to call the base method if applicable.
Expected output: Rectangle class correctly overrides area() and optionally uses super().
Hint: Implement area calculation in Rectangle and optionally call the base method.
Interview Questions
What is inheritance in Python?
InterviewInheritance is a feature in Python where a class (child) inherits attributes and methods from another class (parent), enabling code reuse and hierarchical relationships.
How do you call a parent class method in a subclass?
InterviewYou can call a parent class method using the super() function, for example: super().method_name().
What are the different types of inheritance in Python?
InterviewPython supports single, multiple, multilevel, hierarchical, and hybrid inheritance.
MCQ Quiz
1. What is the primary purpose of inheritance in Python's object-oriented programming?
Select one option to check your answer.
2. What is the role of the super() function in Python inheritance?
Select one option to check your answer.
3. Which of the following is NOT a recognized type of inheritance in Python?
Select one option to check your answer.
Key Takeaways
- Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit attributes and methods from another class.
- In Python, inheritance enables code reuse and the creation of hierarchical relationships between classes.
- This tutorial will guide you through the basics of inheritance in Python with practical examples and explanations.
- Inheritance allows a new class, called a child or subclass, to acquire the properties and behaviors of an existing class, called a parent or superclass.
- This mechanism helps reduce code duplication and makes programs easier to maintain.
Frequently Asked Questions
Can a Python class inherit from multiple classes?
Yes, Python supports multiple inheritance where a class can inherit from more than one parent class.
What happens if a method is not found in the subclass?
Python looks for the method in the parent classes following the method resolution order (MRO). If not found, it raises an AttributeError.
Is it mandatory to call super() in subclass constructors?
It is not mandatory but recommended to call super() to ensure the parent class is properly initialized.
Summary
Inheritance in Python allows classes to derive properties and behaviors from other classes, promoting code reuse and logical design.
You learned about basic inheritance syntax, method overriding, the use of super(), and different inheritance types.
Following best practices and avoiding common mistakes will help you write clean and maintainable object-oriented Python code.





