为什么产量在这种结构中不起作用?

发布于 2025-02-08 01:07:17 字数 455 浏览 1 评论 0原文

我不明白为什么这种屈服结构只会在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

日暮斜阳 2025-02-15 01:07:17

您的__ ITER __功能需要循环。实际上,它只能产生一次,因此您的循环仅打印一个值。

class myRange():
    def __init__(self, first, last):
        self.current = first
        self.last = last

    def __iter__(self):
        while self.current <= self.last:
            yield self.current
            self.current += 1

Your __iter__ function needs to loop. As it is, it only yields once, so your loop only prints one value.

class myRange():
    def __init__(self, first, last):
        self.current = first
        self.last = last

    def __iter__(self):
        while self.current <= self.last:
            yield self.current
            self.current += 1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文