为什么产量在这种结构中不起作用?
我不明白为什么这种屈服结构只会在for循环中进行一次运行:
class myRange():
def __init__(self, first, last):
self.current = first - 1
self.last = last
def __iter__(self):
self.current = self.current + 1
if (self.current <= self.last):
yield self.current
for n in myRange(1, 10):
print(n)
生成:
1
编辑:有点弱问题!我被__ iter __
funciton的名称所欺骗。
I cannot understand why this yield construct gives me only one run in the for loop:
class myRange():
def __init__(self, first, last):
self.current = first - 1
self.last = last
def __iter__(self):
self.current = self.current + 1
if (self.current <= self.last):
yield self.current
for n in myRange(1, 10):
print(n)
which produces:
1
EDIT: Kind of weak question! I was tricked by the name of the __iter__
funciton...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
__ ITER __
功能需要循环。实际上,它只能产生一次,因此您的循环仅打印一个值。Your
__iter__
function needs to loop. As it is, it only yields once, so your loop only prints one value.