Lesson 17 of 30
OOP – Inheritance and Polymorphism
Extending classes, method overriding, super(), and interface-style design.
Inheritance
Inheritance allows a new class (child) to inherit attributes and methods from an existing class (parent):
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
class Cat(Animal): # Cat inherits Animal
def speak(self): # override
print(f"{self.name} says: Meow!")
class Dog(Animal):
def speak(self):
print(f"{self.name} says: Woof!")
pets = [Cat("Whiskers"), Dog("Rex")]
for pet in pets:
pet.speak() # polymorphism
Using super()
class ElectricCar(Car):
def __init__(self, make, model, battery_kw):
super().__init__(make, model) # call parent __init__
self.battery_kw = battery_kw
isinstance() and issubclass()
cat = Cat("Luna")
print(isinstance(cat, Animal)) # True
print(isinstance(cat, Cat)) # True
print(issubclass(Cat, Animal)) # True