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 Enum​
2class Status(Enum):​
3 ACTIVE = 1​
4 BLOCKED = 2​
5print(Status.ACTIVE.name, Status(2))​

Worked example

1from abc import ABC, abstractmethod​
2import math​
3​
4class Shape(ABC):​
5 @abstractmethod​
6 def area(self): ...​
7​
8class Circle(Shape):​
9 def __init__(self, r): self.r = r​
10 def area(self): return round(math.pi * self.r ** 2, 2)​
11​
12class Square(Shape):​
13 def __init__(self, s): self.s = s​
14 def area(self): return self.s ** 2​
15​
16for s in [Circle(1), Square(3)]:​
17 print(type(s).__name__, s.area())​
18​
19try:​
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.