时间:2021-07-01 10:21:17 帮助过:170人阅读
for i in range(1, 5): print i
def fib(n):
a = 0
b = 1
for _ in range(n):
a, b = b, a+b
yield a
谢邀。刚看到问题以为楼主要问in是什么意思。# 以下代码在Python 2中运行
for row in f:
print row
# 完全等价于
itr = f.__iter__() # 获得新的迭代器
while True:
try:
row = itr.next()
except StopIteration:
break
print row
迭代器。循环时, 程序先使用__iter__ (相当于iter(instance))获取具有next方法的对象, 然后通过其返回的对象, 不断调用其next方法, 直到StopIteration错误抛出.
class A:
def __iter__(self):
self.limit = 4
self.times = 0
self.init = 1
return self
def next(self):
if self.times >= self.limit:
raise StopIteration()
else:
x = self.init
self.times += 1
self.init += 1
return x
print 'A>>>>>>'
for x in A():
print x