把开发过程较好的一些代码备份一下,如下代码是关于python中如何创建一个迭代器的代码,应该是对各位有些用途。
class OddIterator(object):
def __init__(self):
self.value = -1
# Required for the for-in syntax
def __iter__(self):
return self
# Returns the next value of the iterator
def next(self):
self.value += 2
return self.value
测试迭代器的next方法
iter = OddIterator()
assert iter.next() == 1
assert iter.next() == 3
assert iter.next() == 5
assert iter.next() == 7
测试forin语法是否正确
iter = OddIterator()
# Prints 1, 3, 5, 7 and 9
for i in iter:
print i
if i >= 9:
break