Skip to the workspace
Pebellslearn by building
Objects  ›  Lesson

Abstraction

Abstraction 20 minAbstraction exposes what an operation promises while leaving its implementation behind an interface.

Abstraction exposes what an operation promises while leaving its implementation behind an interface.

Use abstract base classes where useful and distinguish requiring a method’s name from proving its behavior.

The billing loop depends on a monthly_fee() operation, not on how a product calculates its fee. That separation is an abstraction. An abstract base class can make a missing implementation fail earlier, when an instance is requested. Learn exactly what this check catches, then test the parts of the contract it cannot establish.

A blueprint labelled "Product (ABC): monthly_fee() — abstractmethod"; a Draft class with the method missing hits a stamp reading "REFUSED — TypeError at construction" before it ever reaches the billing list; a Current class with the method filled in passes through a "✓ built" stamp

A contract with a hole in it

Three products, three monthly_fee() methods, one billing loop that never asks which is which — the previous lesson's whole point. But it only works because every product happens to have the method. Nothing wrote that rule down, and nothing checked it. Ship a fourth product with the method misspelled, and the billing loop finds out at month end, in production, holding an object it cannot bill.

The abc module can catch this particular omission. Inherit from ABC and put @abstractmethod immediately above the required method. This marks it as abstract; the ... below is only a placeholder body and does not perform the check itself:

python

Product states a required operation. Current supplies a concrete implementation of that name, so Current() is allowed. The subclass may also inherit a concrete implementation from an intermediate base; each subclass need not rewrite it.

Preparing this topic’s interactive investigation…

Checked at the door — and it can carry real code too

Leave the hole unfilled and Python refuses to build the object at all:

What happens when this runs?
from abc import ABC, abstractmethod

class Product(ABC):
    @abstractmethod
    def monthly_fee(self):
        ...

class Draft(Product):
    pass

print(Draft().monthly_fee())

Duck typing finds an absent operation at the call. Regular subclasses of this ABC are checked for unresolved abstract members when instantiated. That narrows one failure's location; it does not run the method or verify the fee calculation.

An abstract class isn't only holes — it can carry real, shared code that calls the holes it declares:

What does this print?
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        ...

    def describe(self):
        return f"area {self.area()}"

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side

print(Square(3).describe())

An implemented name can still have the wrong contract

This product clears the abstract-method check. Predict which line will fail:

python

constructed appears first. ABC machinery sees that the abstract name has been overridden; it does not compare method signatures or validate return values. Changing the method to accept no extra argument but return "five" would pass construction and the call, then fail when billing tries to add the result to a number. Returning the number 500 instead of 5 might run without any exception and still violate the agreed units.

These are three different checks: completeness of the declared implementation, call compatibility, and correct behavior. A static type checker can help with signatures and annotated return types; example-based tests and clear contracts are still needed for units, edge cases, and effects. The original ABC specification explicitly separates enforced structure from behavioral promises.

Do not turn every TypeError into “abstract class.” A broad try around both construction and billing would mislabel the failure above. Keep the handled operation as small as possible, as in the earlier exception examples. The practice classes below deliberately use missing abstract methods; those fixtures do not make TypeError a universal diagnosis of incompleteness.

Hiding the how

Now define a useful behavioral contract: get(key) returns the stored value or None for a missing key, and lookup does not modify the store. For this example, stored values are numbers, so None is unambiguous. Two stores can provide that contract using different representations:

step through it
1from abc import ABC, abstractmethod
2 
3class Store(ABC):
4 @abstractmethod
5 def get(self, key):
6 ...
7 
8 def get_or(self, key, fallback):
9 found = self.get(key)
10 return fallback if found is None else found
11 
12class DictStore(Store):
13 def __init__(self):
14 self.rows = {"a": 1}
15 
16 def get(self, key):
17 return self.rows.get(key)
18 
19class PairStore(Store):
20 def __init__(self):
21 self.rows = [("a", 1)]
22 
23 def get(self, key):
24 for k, v in self.rows:
25 if k == key:
26 return v
27 return None
28 
29for store in (DictStore(), PairStore()):
30 print(store.get_or("a", 0), store.get_or("z", 0))

get_or only calls get; it never accesses rows. That is what lets both stores reuse it. A stored 0 must remain 0, so it checks found is None rather than using found or fallback. This is a contract detail, not a storage detail.

A database-backed implementation could preserve this caller if it preserved the same behavior. Database timeouts, asynchronous calls, or a different missing-value policy would need an explicit decision; inheritance does not make those differences disappear. If None later becomes a valid stored value, the current contract can no longer distinguish “stored None” from “missing.” Choose a distinct sentinel or another result shape before extending it.

For an independent check, add the same "zero": 0 entry to both stores. Run each through a common check that expects 1 for "a", 0 for "zero", and a supplied fallback for an unknown key, then repeats those reads. Repeatability is evidence that these reads did not consume entries. A third store must pass the same checks without the checks inspecting .rows.

When not to reach for it

The billing loop can work through duck typing alone. Use ABC when shared base behavior and an explicit required-implementation check are useful. A small function accepting a compatible object does not automatically need a hierarchy.

For optional static checking without requiring inheritance, typing.Protocol describes a structural interface. Type annotations do not themselves enforce that contract at runtime. Even an optional @runtime_checkable protocol checks attribute presence, not complete signatures or behavior. Treat these tools as different forms of evidence, not interchangeable guarantees.

Quick practice

Name the method wrong and you haven't implemented the contract — you've added an unrelated method and left the hole open:

broken — fix itTypeError

Read the error — it names the method that's missing. Then make it print fee 0.0.

What happens when this runs?
from abc import ABC, abstractmethod

class Handler(ABC):
    @abstractmethod
    def handle(self, x):
        ...

h = Handler()

🎯 Your turn

Define an abstract Product with an abstract label() and a concrete summary() returning f"{self.label()} account". Give Current and Savings their labels; leave Draft without one. Write try_open(kind) returning that product's summary, or "incomplete" if the class cannot be built:

  • try_open("current") → "current account"
  • try_open("savings") → "savings account"
  • try_open("draft") → "incomplete"

Hint — the failure is a TypeError, and it happens on Draft(), before any method is called. Wrap the construction, not the summary().

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below builds a store with two completely different insides, and a month-end run where a broken product never even reaches the list.

Your task
Define an abstract Product with an abstract label() and a concrete summary() returning f"{self.label()} account". Give Current and Savings their labels; leave Draft without one. Write try_open(kind) returning that product's summary, or "incomplete" if the class cannot be built. Example: try_open("draft") → "incomplete".

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upDeclare the hole, then fill it

Define Shape(ABC) with an abstract area(). Define Square(Shape) built from a side, implementing area(). Write square_area(side) returning that area.

abstractionabc
DrillThe contract bites

Define Report(ABC) with an abstract render(). Define Html(Report) implementing it, and Draft(Report) which does not. Write can_build(kind) returning True if the named class can be instantiated and False if it raises.

abstractionabcexceptions
BuildThe base owns the algorithm

Define Exporter(ABC) with an abstract body() and a concrete document() returning f"<{self.body()}>". Define Csv(Exporter) whose body is "a,b" and Json(Exporter) whose body is '{"a": 1}'. Write documents() returning both documents as a list, Csv first.

abstractionabcpolymorphism
BossTwo insides, one contract

Define Store(ABC) with an abstract get(key) and a concrete get_or(key, fallback) returning the fallback when get gives None. Define DictStore holding {"a": 1, "b": 2} in a dict and PairStore holding the same data as a list of pairs. Write lookup(backend, key) — "dict" or "pairs" — returning the value, or "missing".

abstractionabcpolymorphism
CapstoneNo product bills by accident

Define Account(ABC) built from a balance, with an abstract monthly_fee() and a concrete after_month() returning the balance minus the fee, rounded to 2 decimals. Define Current (fee 5.0), Savings (fee 0.0) and Draft, which never implements the fee. Write run_month(entries) where entries look like [["current", 100]], returning each balance after the month — or "incomplete" for a product that cannot be built.

abstractionabcpolymorphismexceptions
Project context and further resources
You're building a piece ofA bank account that can't go wrong
This piece — Product(ABC): A product that forgets its fee is refused at construction, not at 3am.
Scenario A fourth product ships with monthly_fee() misspelled. Nothing complains until a customer's statement crashes at 3am — by which time the broken object is already sitting in a list somewhere.
try_open.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
try_open(kind) → strOpen the named product, or report that it never honoured the contract.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.