... print(stack1.item(i), end=' ')
m a p s >>>
A Stack Class
Perhaps the biggest drawback of the module-based stack is that it supports only a single
stack object. All clients of the stack module effectively share the same stack. Sometimes
we want this feature: a stack can serve as a shared-memory object for multiple modules.
But to implement a true stack datatype that can generate independent objects, we need
to use classes.
To illustrate, let’s define a full-featured stack class. The Stack class shown in Exam-
ple 18-2 defines a new datatype with a variety of behaviors. Like the module, the class
uses a Python list to hold stacked objects. But this time, each instance gets its own list.
The class defines both “real” methods and specially named methods that implement
common type operations. Comments in the code describe special methods.
Example 18-2. PP4E\Dstruct\Basic\stack2.py
"a multi-instance stack class"
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)
self.reverse() # undo push's order reversal
def push(self, obj): # methods: like module + self
self.stack = [obj] + self.stack # top is front of list
def pop(self):
if not self.stack: raise error('underflow')
top, *self.stack = self.stack
return top
def top(self):
if not self.stack: raise error('underflow')
return self.stack[0]
def empty(self):
return not self.stack # instance.empty()
overloads
def repr(self):
return '[Stack:%s]' % self.stack # print, repr(),..
def eq(self, other):
return self.stack == other.stack # '==', '!='?
def len(self):
1364 | Chapter 18: Data Structures