offset −1 (top is end-of-list here). Compared to using built-in lists directly, this class
incurs some performance degradation for the extra method calls, but it supports future
changes better by encapsulating stack operations.
Example 18-5. PP4E\Dstruct\Basic\stack4.py
"optimize with in-place list operations"
class error(Exception): pass # when imported: local exception
class Stack:
def init(self, start=[]): # self is the instance object
self.stack = [] # start is any sequence: stack...
for x in start: self.push(x)
def push(self, obj): # methods: like module + self
self.stack.append(obj) # top is end of list
def pop(self):
if not self.stack: raise error('underflow')
return self.stack.pop() # like fetch and delete stack[-1]
def top(self):
if not self.stack: raise error('underflow')
return self.stack[-1]
def empty(self):
return not self.stack # instance.empty()
def len(self):
return len(self.stack) # len(instance), not instance
def getitem(self, offset):
return self.stack[offset] # instance[offset], in, for
def repr(self):
return '[Stack:%s]' % self.stack
This version works like the original in module stack2, too; just replace stack2 with
stack4 in the previous interaction to get a feel for its operation. The only obvious dif-
ference is that stack items are in reverse when printed (i.e., the top is the end):
>>> from stack4 import Stack
>>> x = Stack()
>>> x.push('spam')
>>> x.push(123)
>>> x
[Stack:['spam', 123]]
>>>
>>> y = Stack()
>>> y.push(3.1415)
>>> y.push(x.pop())
>>> x, y
1370 | Chapter 18: Data Structures