>>> 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)
发布评论
评论(1)
如果您的语言具有引用语义,并且赋值通常是引用赋值,那么您需要选项 1。
这就是 Python 中发生的情况,其中生成是对象,而赋值是 引用赋值(即使您调用 .next() 来检索下一个值,而不是“调用”生成器)。
以下是 Python 中的行为方式的简要演示:
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: