Inheritance & Polymorphism
Inheritance
A subclass gets everything from its parent class and can add or change behaviour:
class Cat(Animal):
- Override a method by defining it again in the subclass.
- Call the parent's version with
super(), especially in__init__:super().__init__(name). isinstance(tom, Animal)isTruefor subclasses too.
Polymorphism
Different classes respond to the same method call in their own way. Code that calls animal.speak() works with any animal, without if checks for each type.
Duck typing
Python doesn't require a shared parent: if an object has the method you call, it works. "If it walks like a duck and quacks like a duck…"
Abstract base classes
Use from abc import ABC, abstractmethod to force subclasses to implement certain methods.
💡 Prefer composition (a Car has an Engine) when "is-a" doesn't fit. Deep inheritance trees get hard to follow.
▶️ Runs in the app.
Example
from abc import ABC, abstractmethod
class Animal(ABC):
def __init__(self, name):
self.name = name
@abstractmethod
def speak(self):
...
def introduce(self):
return f"I am {self.name} and I say {self.speak()}"
class Cat(Animal):
def speak(self):
return "Meow"
class Cow(Animal):
def __init__(self, name, spots):
super().__init__(name) # reuse the parent's setup
self.spots = spots
def speak(self):
return "Moo"
for animal in [Cat("Tom"), Cow("Daisy", spots=12)]:
print(animal.introduce()) # polymorphism
# I am Tom and I say Meow
# I am Daisy and I say Moo
print(isinstance(Cat("Kit"), Animal)) # True