Lecture 3
Lecture 3
LESSON 3_1
Inheritance
© YCI – 2025.
BIT 1203 2/22/2025
What is Inheritance?
2
◻ Definition:
Mechanism where a child class (subclass) inherits
attributes/methods from a parent class
(superclass).
◻ Key Benefits:
Code reusability.
Hierarchical modeling (e.g., Dog is an Animal).
◻ Parent class
class ParentClass:
def parent_method(self):
print("Parent method")
◻ Child class Inherits from ParentClass
class ChildClass(ParentClass):
def child_method(self):
print("Child method")
◻ Single Inheritance:
class Parent: ...
class Child(Parent): ...
◻ Multiple Inheritance:
class Father: ...
class Mother: ...
class Child(Father, Mother): ...
◻ Multilevel Inheritance:
class Grandparent: ...
class Parent(Grandparent): ...
class Child(Parent): ...
◻ Concept:
Redefine a parent method in the child class.
◻ Example:
class Animal:
def speak(self):
print("Generic animal sound")
class Dog(Animal):
def speak(self): # Override
print("Bark!")
© YCI – 2025. 2/22/2025
The super() Function
6
◻ Purpose:
Call parent class methods from the child.
◻ Example (Constructor):
class Vehicle:
def __init__(self, type):
self.type = type
class Car(Vehicle):
def __init__(self, type, brand):
super().__init__(type) # Call parent's __init__
self.brand = brand
◻ Use Case:
Avoid rewriting parent logic.
◻ What is MRO?
The order in which Python searches for methods in
inheritance hierarchies.
◻ Check MRO:
print(ChildClass.__mro__)
◻ Example (Multiple Inheritance):
class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass
print(D.__mro__) # Order: D → B → C → A → object
◻ Transport
Source
Destination
Fare
Time of travel
◻ By road
Car
Bus
bicycle
◻ By air
Boeing
Bombardier
◻ By rail
Steam train
Electric train