CS 112 › Lesson 5 of 10

Abstract Classes & Interfaces

Lesson 5 · OKSTEM College · Associate of Science in Computer Science

Abstract Classes with abc

An abstract class defines a contract — methods that every subclass must implement. You cannot instantiate an abstract class directly. Python's abc module provides ABC and @abstractmethod.

from abc import ABC, abstractmethod class Serializer(ABC): @abstractmethod def serialize(self, data) -> str: """Convert data to a string format.""" @abstractmethod def deserialize(self, text: str): """Parse a string back to data.""" # This would raise TypeError — can't instantiate ABC directly # s = Serializer() ← TypeError
import json class JSONSerializer(Serializer): def serialize(self, data) -> str: return json.dumps(data) def deserialize(self, text): return json.loads(text) s = JSONSerializer() # OK — all abstract methods implemented print(s.serialize({"name": "Alice"})) # {"name": "Alice"}

Forgetting one @abstractmethod? Python raises TypeError: Can't instantiate abstract class … with abstract method … at the point you try to create the object — not at definition time.

Abstract Properties

Combine @property and @abstractmethod to force subclasses to expose a computed attribute.

from abc import ABC, abstractmethod class Shape(ABC): @property @abstractmethod def area(self) -> float: ... def describe(self): print(f"Area = {self.area:.2f}") # concrete method using abstract prop class Square(Shape): def __init__(self, side): self.side = side @property def area(self): return self.side ** 2 Square(4).describe() # Area = 16.00

Practice Problems

1. Why can't you instantiate an abstract class directly?

Because it has one or more @abstractmethod stubs with no implementation. The ABC metaclass raises TypeError to enforce that every concrete subclass provides real implementations before objects are created.

2. Write an abstract class Notifier with abstract method send(message), then implement EmailNotifier and SMSNotifier.

from abc import ABC, abstractmethod class Notifier(ABC): @abstractmethod def send(self, message: str): ... class EmailNotifier(Notifier): def send(self, message): print(f"Email: {message}") class SMSNotifier(Notifier): def send(self, message): print(f"SMS: {message}")

Knowledge Check

What happens when you try to instantiate an abstract class?

Abstract methods have no default; that's the whole point.
Correct — Python refuses to create an instance with unimplemented abstract methods.
ABCs enforce hard errors, not warnings.
Nothing is skipped; the error is immediate.
Recap: ABCs enforce a contract at instantiation time. If any @abstractmethod is not implemented, you get TypeError.

To create an abstract class in Python you inherit from

Not a built-in; the correct class is ABC from the abc module.
Correct — from abc import ABC, then class MyABC(ABC).
No such keyword argument exists.
Python has no Interface keyword; use ABC + abstractmethod.
Recap: from abc import ABC, abstractmethod. Inherit from ABC. Decorate stubs with @abstractmethod.

A concrete class is

Method count is irrelevant.
Correct — once all @abstractmethod stubs are implemented, the class is concrete.
Concrete just means 'not abstract'.
Class variables don't affect abstract status.
Recap: abstract = has unimplemented stubs. Concrete = every method has an implementation. You can only __init__ a concrete class.

An abstract property requires decorators in this order

Wrong order — this doesn't work correctly.
Correct — stack @property on top, @abstractmethod below.
No such built-in decorator exists.
Decorator order matters in Python; @property must come first.
Recap: correct stacking: @property on the outer line, @abstractmethod on the inner line.

ABCs are most useful for

ABCs are a design tool, not a performance tool.
Correct — they guarantee every subclass exposes the same set of methods.
ABCs catch missing methods but not logic bugs.
ABCs don't affect whether you call super().
Recap: use ABCs when you have a family of classes that must all support the same operations — Serializer, Notifier, Shape, etc.

← PreviousNext →