【发布时间】:2021-04-10 18:12:49
【问题描述】:
我不明白为什么当我取消注释 if False: yield 时 __iter__ 的行为会发生变化。条件永远不成立,为什么结果会发生变化?
class Example:
def __init__(self):
self.lst = [1,2,3]
self.size = 3
def __iter__(self):
self.n = 0
#if False: yield
return self
def __next__(self):
self.n += 1
if self.n > self.size:
raise StopIteration
return self.lst[self.n-1]
ex = Example()
for i in ex:
print(i)
在这段代码中,一切都按预期工作,并打印出列表。
如果我取消注释 __iter__ 方法中的 if False: yield,那么迭代器将停止工作并且不会打印任何内容,即使该行从未被执行。
【问题讨论】:
-
你发现的是 Python 中 Iterator 和 Iterable 对象之间的细微差别