Sub topic 2
Interface versus Implementation
Assume you know Python classes, exceptions, references, and basic Big-O notation.
An interface describes what an object can do and what each operation promises. An implementation is the internal code and data structure that fulfills those promises. Client code should depend on the interface, not on internal fields.
A Worked Example: The Stack ADT
A stack is an abstract data type (ADT) whose items follow last-in, first-out order. The most recently pushed item is the next item removed.
Its interface specifies these operations:
push(item): add an item.pop(): remove and return the top item.peek(): return the top item without removing it.is_empty(): report whether the stack has no items.pop()andpeek()raiseIndexErrorwhen the stack is empty.
The interface does not say whether the stack uses a list, linked nodes, or another representation.
from abc import ABC, abstractmethod
class Stack(ABC):
@abstractmethod
def push(self, item):
pass
@abstractmethod
def pop(self):
pass
@abstractmethod
def peek(self):
pass
@abstractmethod
def is_empty(self):
passTwo Implementations of the Same Stack
ListStack stores the top at the end of a Python list. LinkedStack stores the top in a linked node. Both satisfy the same behavioral specification.
class ListStack(Stack):
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek at empty stack")
return self._items[-1]
def is_empty(self):
return not self._items
class LinkedStack(Stack):
class Node:
def __init__(self, value, next_node):
self.value = value
self.next = next_node
def __init__(self):
self._head = None
def push(self, item):
self._head = self.Node(item, self._head)
def pop(self):
if self._head is None:
raise IndexError("pop from empty stack")
value = self._head.value
self._head = self._head.next
return value
def peek(self):
if self._head is None:
raise IndexError("peek at empty stack")
return self._head.value
def is_empty(self):
return self._head is NoneBoth implementations perform push, pop, and peek in constant time, written O(1). Their storage strategies differ, but their observable behavior is the same.
Writing Clients That Depend Only on the Interface
A client uses only promised operations. It does not read _items or _head, so either implementation can be supplied.
def reverse(items, stack):
for item in items:
stack.push(item)
result = []
while not stack.is_empty():
result.append(stack.pop())
return result
print(reverse([1, 2, 3], ListStack())) # [3, 2, 1]
print(reverse([1, 2, 3], LinkedStack())) # [3, 2, 1]Exercise
Why can reverse use either stack implementation without modification?
Show answer
It calls only the operations promised by the Stack interface and does not depend on either internal representation.