当生成器函数被赋值时会发生什么?

发布于 2024-08-09 00:38:54 字数 1431 浏览 9 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

薆情海 2024-08-16 00:38:54

如果您的语言具有引用语义,并且赋值通常是引用赋值,那么您需要选项 1。

这就是 Python 中发生的情况,其中生成对象,而赋值 引用赋值(即使您调用 .next() 来检索下一个值,而不是“调用”生成器)。

以下是 Python 中的行为方式的简要演示:

>>> def gen():
...   for i in range(42):
...     yield i
... 
>>> f = gen().next
>>> a = f()
>>> b = f()
>>> g = f
>>> c = g()
>>> d = f()
>>> a, b, c, d
(0, 1, 2, 3)

If you have reference semantics in your language, and assignment is usually reference assignment, then you want option 1.

This is what happens in Python, where generates are objects, and assignment is reference assignment (even though you invoke .next() to retrieve the next value, rather than "calling" the generator).

Here is a brief demonstration how this behaves in Python:

>>> def gen():
...   for i in range(42):
...     yield i
... 
>>> f = gen().next
>>> a = f()
>>> b = f()
>>> g = f
>>> c = g()
>>> d = f()
>>> a, b, c, d
(0, 1, 2, 3)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文