设计模式之迭代模式
class BaseIterator: """迭代器""" def __init__(self, data): self.__data = data self.toBegin() def toBegin(self): """将指针移至起始位置""" self.__curIdx = -1 def toEnd(self): """将指针移至结尾位置""" self.__curIdx = len(self.__data) def next(self): """移动至下一个元素""" if(self.__curIdx < len(self.__data) - 1): self.__curIdx += 1 return True else: self.__curIdx += 1 return False def prevoius(self): """移动至上一个元素""" if(self.__curIdx > 0): self.__curIdx -= 1 return True else: self.__curIdx -= 1 return False def current(self): """获取当前的元素""" return self.__data[self.__curIdx] if (self.__curIdx < len(self.__data)) and self.__curIdx >= 0 else None class NumberSequence: """生成一个间隔为step的数字系列""" def __init(self, init, step, max=100): self.__data = init self.__step = step self.__max = max def __iter__(self): return self def __next__(self): if(self.__data < self.__data + self.__step): temp = self.__data self.__data += self.__step return temp else: raise StopIteration if __name__ == "__main__": print("从前往后遍历:") iterator = BaseIterator(range(10)) while(iterator.next()): customer = iterator.current() print(customer, end="\t") print() print("从后往前遍历:") while(iterator.prevoius()): customer = iterator.current() print(customer, end="\t")