错误实例
# 1. 简单的迭代器
class SimpleCounter(object):
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
'returns itself as an iterator object'
return self
def next(self):
'Returns the next value till current is lower than end'
if self.current > self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1
# # 2. 访问一
c = SimpleCounter(1, 3)
# print(c.next())
# print(c.next())
# print(c.next())
# # print(c.next())
# 3. 访问二
for entry in iter(c):
print(entry)
修改:python3.0 中
迭代器的规则原来是发生了一些变化的。在新的迭代器规则中,迭代器对象应该实现__next__方法,而不是next
# 1. 简单的迭代器
class SimpleCounter(object):
def __init__(self, start, end):
self.current = start
self.end = end
def __iter__(self):
'returns itself as an iterator object'
return self
def next(self):
'Returns the next value till current is lower than end'
if self.current > self.end:
raise StopIteration
else:
self.current += 1
return self.current - 1
# # 2. 访问一
c = SimpleCounter(1, 3)
print(c.next())
print(c.next())
print(c.next())
# print(c.next())
# 3. 访问二
#for entry in iter(c):
# print(entry)