05. Understanding Inheritance in Python: Parent, Child, super(), and Method Overriding
Introduction
Inheritance is a key concept in object-oriented programming (OOP). In Python, inheritance lets you define a new class (child or derived class) that reuses or extends the behavior and attributes of an existing class (parent or base class). This promotes code reuse, modularity, and cleaner design.
Parent Class and Child Class
Any class can serve as a parent class (also called base class). To derive a child class (also called subclass), you list the parent class in parentheses after the class name:
In this example, Student inherits all attributes and methods from Person. Even though Student doesn’t define anything new (using pass), it still has firstname, lastname, and printname() via inheritance.
Overriding the Constructor (__init__)
If you define your own __init__ in the child class, it overrides the parent’s constructor. That means the parent’s __init__ is not automatically called anymore.
To keep the parent’s initialization logic, you can explicitly call the parent’s __init__ method. Two approaches:
1. Using the parent class name:
2. Using super():
Using super() is more maintainable and avoids explicitly naming the parent class.
Adding New Properties and Methods
A child class can define additional properties or methods beyond what it inherits. For example:
Here, Student has a new attribute graduationyear and a method welcome. The inherited printname() still works for Student objects.
You can also override methods from the parent class by redefining them in the child class with the same name. This is called method overriding.
Use Cases and Design Tips
- Use inheritance when there is an “is-a” relationship (e.g. Student is a Person).
- Use super() to invoke parent behavior while extending it.
- Avoid excessive inheritance — deep hierarchies can reduce clarity.
- Favor composition over inheritance when an object “has a” relationship (i.e. include an instance of another class rather than inheriting) if appropriate. (This is a broader OOP design guideline beyond the W3Schools tutorial.)
Summary
Inheritance in Python allows a child class to automatically gain attributes and methods from a parent class, enabling code reuse and logical class structure. You can override the parent’s constructor, use super() to call parent methods, and add or override functionality in the child class. With a solid understanding of inheritance and method overriding, you can design more elegant and maintainable Python code.
05. Understanding Inheritance in Python Parent Child super and Method Overriding
coldshadow44 on 2025-10-11
(0)