Inheritance and Its Types
Inheritance allows a new class (called a child or derived class) to reuse the attributes and methods of an existing class (called a parent or base class), while also adding or overriding functionality of its own.
Basic Inheritance
class Person:
def __init__(self, name):
self.name = name
def introduce(self):
print(f"I'm {self.name}")
class Student(Person):
def __init__(self, name, course):
super().__init__(name)
self.course = course
s = Student("Abhay", "Data Science")
s.introduce() # inherited from Person
The super().__init__(name) call lets the child class reuse the parent class's constructor logic instead of duplicating it.
Types of Inheritance
- Single Inheritance - a child class inherits from exactly one parent class
- Multiple Inheritance - a child class inherits from more than one parent class simultaneously
- Multilevel Inheritance - a class inherits from a child class, which itself inherited from another parent, forming a chain
- Hierarchical Inheritance - multiple child classes all inherit from the same single parent class
# Multiple Inheritance example
class Swimmer:
def swim(self):
print("Swimming")
class Runner:
def run(self):
print("Running")
class Triathlete(Swimmer, Runner):
pass
t = Triathlete()
t.swim()
t.run()
Inheritance should be used when a genuine "is-a" relationship exists between classes (a Student "is a" Person). If classes are only loosely related, composition - building objects that contain other objects - is often a cleaner design choice.
Coming Up Next
Next, you'll dig deeper into Method Resolution Order - how Python decides which method to call when multiple inherited classes define one with the same name.