Abstract Base Class

Context: FIT1008_MOC · the Python mechanism encoding an Abstract Data Type (ADT)‘s contract as enforced code · base of Stack (ADT)/Queue (ADT)

Quick Revision

  • 🎯 Objective: encode a contract in code ➔ some methods shared, others abstract; cannot be instantiated.
  • 📦 Core Components: inherit ABC + @abstractmethod | storage-independent concrete vs storage-dependent abstract.
  • ⚡ Key Constraint: instantiation fails until every abstract method is implemented ➔ early, checked guarantees.

📝 Core

1. The ABC (Enforced Contract)

  • Mechanism ➔ some methods implemented (shared), others abstract for subclasses ➔ turns an Abstract Data Type (ADT) into enforced code.
  • Cannot instantiate ➔ exists to be inherited; Stack()TypeError, ArrayStack(6) ➔ OK.
  • Python syntax ➔ inherit ABC, decorate unimplemented methods @abstractmethod.

2. The Concrete/Abstract Split

  • Concrete (base) ➔ storage-independent logic (__len__, is_empty, clear) reads shared length ➔ written once, inherited.
  • Abstract ➔ storage-dependent logic (push/pop/peek/is_full) ➔ only a subclass that knows its storage can implement it.

⚙️ Core Implementation

🔹 Stack(ABC, Generic[T])

⚖️ Core Decision Matrix

Abstract methodConcrete method
Body?❌ (...)
Decorator@abstractmethodnone
Subclass must override?optional
Blocks instantiation?✅ until implemented

When It Flips: three ways to satisfy an interface — ABC (nominal, enforced, allows shared code), pure interface (Java interface, contract only), duck typing (structural, flexible but unchecked until call time). ABCs trade flexibility for early, checked guarantees.

📊 Exam Execution Trace

Manual Execution Trace

Which methods go where:

Step / StateMethodDepends onPlacement
0 (Init)
1is_empty/__len__shared lengthconcrete (base)
2clearshared stateconcrete (base)
3push/pop/peekbacking storageabstract
4is_fullstorage capacityabstract

Applied Exercise

Problem: Show how the ABC enforces the contract at instantiation. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: the ABC blocks instantiation until the full abstract set is implemented — a compile/instantiation-time guarantee.

🧠 Active Recall