以下定义了一个全功能的堆栈类: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
这里模拟了一个栈顶在列表末尾的堆栈。
进栈时,利用列表的append方法将数据添加至末尾;出栈时,则利用pop方法将末尾的元素删除并返回;
类中的top方法还可以仅返回栈顶元素而不做出栈操作;而empty方法可以检测当前栈是否为空;
另外,该类还实现了检测栈内元素个数、获取任意位置的元素等。
该实例来自于《Programming Python》4th Edition