L4·OOP & Errors
🧬Abstract Classes, Enums & Polymorphism
Design contracts with ABC, fixed choices with Enum, duck typing.
abcabstractmethodenumpolymorphismduck typing
§ 1Polymorphism
Different classes expose the same method name; calling code doesn't care which class it got. Python leans on duck typing: 'if it has .area(), it's a shape'.
§ 2Abstract base classes
Inherit from ABC and mark methods with @abstractmethod. Subclasses that don't implement them can't be instantiated — the contract is enforced.
§ 3Enum
Enum gives named constants that can't be mistyped: Color.RED instead of the string 'red'. Iterate with for c in Color.
1from enum import Enum2class Status(Enum):3 ACTIVE = 14 BLOCKED = 25print(Status.ACTIVE.name, Status(2))Worked example
1from abc import ABC, abstractmethod2import math34class Shape(ABC):5 @abstractmethod6 def area(self): ...78class Circle(Shape):9 def __init__(self, r): self.r = r10 def area(self): return round(math.pi * self.r ** 2, 2)1112class Square(Shape):13 def __init__(self, s): self.s = s14 def area(self): return self.s ** 21516for s in [Circle(1), Square(3)]:17 print(type(s).__name__, s.area())1819try:20 Shape()21except TypeError as e:22 print("blocked:", e)Try it live · Python runs in your browser
Loading playground…
Checkpoint quiz
Question 1 / 2
Instantiating a class with an unimplemented @abstractmethod raises:
Lesson test
Take an 8-question test on “Abstract Classes, Enums & Polymorphism” — concepts, output prediction, bug spotting and interview questions.