class stack(object): def __init__(self): self.stack = [] def push(self,str1): self.stack.append(str1) def pop(self): return self.stack.pop() def length(self): return len(self.stack)
应该怎么遍历这个堆栈呢?
类只有实现了__iter__() 和next()方法(python3改为__next__()),生成的实例才能迭代
具有__iter__ 和next方法的对象叫迭代器
python2.7.5的代码
class stack(object): """只有实现了__iter__和next方法的类生成的实例才可以迭代""" def __init__(self): self.stack = [] def push(self,str1): self.stack.append(str1) def pop(self): return self.stack.pop() def length(self): return len(self.stack) def __iter__(self): return self def __next__(self): try: return self.stack.pop() except IndexError: raise StopIteration
python3.3.2的代码
class stack(object): """只有实现了__iter__和next方法的类生成的实例才可以迭代""" def __init__(self): self.stack = [] def push(self,str1): self.stack.append(str1) def pop(self): return self.stack.pop() def length(self): return len(self.stack) def __iter__(self): return self def __next__(self): try: return self.stack.pop() except IndexError: raise StopIteration