Abstract Classes

An abstract class is a class that cannot be instantiated directly. It defines a contract — a set of methods that every subclass must implement. This ensures all subclasses share a consistent interface.

Why Abstract Classes?

Imagine a Shape class. "Shape" is too generic to have a meaningfularea() — but every concrete shape (rectangle, circle, triangle) must be able to calculate its area. An abstract class enforces this rule.

from abc import ABC, abstractmethod
class Shape(ABC):  # inherits from ABC
    @abstractmethod
    def area(self): pass  # no implementation — just a contract
# Shape()  →  TypeError: Can't instantiate abstract class

Concrete Subclasses

A concrete class implements all abstract methods. Once it does, it can be instantiated normally.

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w, self.h = w, h
    def area(self):
        return self.w * self.h  # must implement all abstract methods
    def perimeter(self):
        return 2 * (self.w + self.h)
r = Rectangle(4, 5)
print(r.area())  # → 20

If a subclass misses any abstract method, Python raises a TypeErrorwhen you try to instantiate it — protecting you from incomplete implementations.

Polymorphism with Abstract Classes

shapes = [Rectangle(4, 5), Circle(3), Square(2)]
for s in shapes:
    print(f"Area: {s.area():.2f}")
Area: 20.00
Area: 28.27
Area: 4.00

The loop works on any Shape — today or in the future — because the abstract class guarantees area() exists.

Your Task

  1. Shape is already defined as abstract with area() and perimeter() — do not change it
  2. Write class Square(Shape): with __init__(self, side)
  3. Implement area(self)self.side ** 2
  4. Implement perimeter(self)4 * self.side

Square(5).area() should return 25 and Square(5).perimeter() should return 20.

Section 1/4Why Abstract Classes?

Why Abstract Classes?

Imagine a Shape class. "Shape" is too generic to have a meaningfularea() — but every concrete shape (rectangle, circle, triangle) must be able to calculate its area. An abstract class enforces this rule.

Abstract Classes

An abstract class is a class that cannot be instantiated directly. It defines a contract — a set of methods that every subclass must implement. This ensures all subclasses share a consistent interface.

Why Abstract Classes?

Imagine a Shape class. "Shape" is too generic to have a meaningfularea() — but every concrete shape (rectangle, circle, triangle) must be able to calculate its area. An abstract class enforces this rule.

from abc import ABC, abstractmethod
class Shape(ABC):  # inherits from ABC
    @abstractmethod
    def area(self): pass  # no implementation — just a contract
# Shape()  →  TypeError: Can't instantiate abstract class

Output:

Click "Check" to run your code.