intermediateOOP

Inheritance & Polymorphism

Extend classes, override methods, and achieve polymorphism.

01Basic Inheritance

Create a child class that inherits attributes and methods from a parent class.

Python
1class Animal:
2 def __init__(self, name):
3 self.name = name
4
5 def speak(self):
6 raise NotImplementedError
7
8class Cat(Animal):
9 def speak(self):
10 return f"{self.name}: Meow!"
11
12class Dog(Animal):
13 def speak(self):
14 return f"{self.name}: Woof!"
15
16animals = [Cat("Whiskers"), Dog("Rex")]
17for animal in animals:
18 print(animal.speak())
Output
Whiskers: Meow!
Rex: Woof!

02super() and Method Overriding

Use super() to call parent class methods and extend behavior.

Python
1class Vehicle:
2 def __init__(self, brand, speed):
3 self.brand = brand
4 self.speed = speed
5
6class ElectricCar(Vehicle):
7 def __init__(self, brand, speed, battery):
8 super().__init__(brand, speed)
9 self.battery = battery
10
11 def info(self):
12 return f"{self.brand} | {self.speed}km/h | {self.battery}kWh"
13
14tesla = ElectricCar("Tesla", 250, 100)
15print(tesla.info())
Output
Tesla | 250km/h | 100kWh