[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

This module creates a list object (stack) and exports functions to manage access to it.
The stack is declared global in functions that change it, but not in those that just ref-
erence it. The module also defines an error object (error) that can be used to catch
exceptions raised locally in this module. Some stack errors are built-in exceptions: the
method item triggers IndexError for out-of-bounds indexes.


Most of the stack’s functions just delegate the operation to the embedded list used to
represent the stack. In fact, the module is really just a simple wrapper around a Python
list. Because this extra layer of interface logic makes clients independent of the actual
implementation of the stack, though, we’re able to change the stack later without im-
pacting its clients.


As usual, one of the best ways to understand such code is to see it in action. Here’s an
interactive session that illustrates the module’s interfaces—it implements a stack of
arbitrary Python objects:


C:\...\PP4E\Dstruct\Basic> python
>>> import stack1
>>> stack1.push('spam')
>>> stack1.push(123)
>>> stack1.top()
123
>>> stack1.stack
[123, 'spam']
>>> stack1.pop()
123
>>> stack1.dump()
<Stack:['spam']>
>>> stack1.pop()
'spam'
>>> stack1.empty()
True
>>> for c in 'spam': stack1.push(c)
...
>>> while not stack1.empty():
... print(stack1.pop(), end=' ')
...
m a p s >>>
>>> stack1.pop()
stack1.error: stack underflow

Other operations are analogous, but the main thing to notice here is that all stack
operations are module functions. For instance, it’s possible to iterate over the stack, but
we need to use counter-loops and indexing function calls (item). Nothing is preventing
clients from accessing (and even changing) stack1.stack directly, but doing so defeats
the purpose of interfaces like this one:


>>> for c in 'spam': stack1.push(c)
...
>>> stack1.dump()
<Stack:['m', 'a', 'p', 's']>
>>>
>>> for i in range(stack1.length()):

Implementing Stacks| 1363
Free download pdf