Lesson 5 of 7 · Classes and Objects · 3 min read · Updated

Abstraction and abstract classes

Describing what every kind of object must do, while leaving how it does it to each one.

Abstraction means working with what something does and hiding how. You call print() without knowing how it reaches the screen. In classes, an abstract class writes the promise down: every subclass must provide these methods.

python
from abc import ABC, abstractmethod

class Payment(ABC):
    @abstractmethod
    def pay(self, amount):
        ...

    def receipt(self, amount):
        return f"Paid ₹{amount} by {self.pay(amount)}"

class UPI(Payment):
    def pay(self, amount):
        return "UPI"

class Card(Payment):
    def pay(self, amount):
        return "card"

for method in [UPI(), Card()]:
    print(method.receipt(500))

try:
    Payment()
except TypeError:
    print("Cannot create a Payment directly")
Output
Paid ₹500 by UPI
Paid ₹500 by card
Cannot create a Payment directly
  • Inheriting from ABC (from the standard abc module) makes Payment abstract.
  • @abstractmethod marks pay as required. The ... body is a placeholder that is never run.
  • An abstract class cannot be created itself — only its complete subclasses can.
  • Ordinary methods such as receipt are shared, and can rely on pay existing.
python
from abc import ABC, abstractmethod

class Payment(ABC):
    @abstractmethod
    def pay(self, amount):
        ...

class Cash(Payment):
    pass

try:
    Cash()
except TypeError:
    print("Cash must define pay() first")
Output
Cash must define pay() first

Note

Compare the NotImplementedError approach in the Polymorphism lesson: it fails only when the missing method is called, perhaps weeks later. An abstract class fails the moment an incomplete object is created, which is far easier to track down.

A class inherits from an abstract class but does not define one of its abstract methods. What happens?

Try this now

  1. Write an abstract Shape with abstract area() and perimeter(), then Circle and Square subclasses.
  2. Add a describe() method to Shape that uses both abstract methods, and call it on each subclass.

Create a free account to save your progress, or sign in.