函数体中 yield 关键字的存在是否会改变函数的工作方式?
Does the presence of yield keyword in the body of function change how the function works?
似乎如果函数体中的任何地方至少有一个 yield,那么即使没有达到 yield,它也会 return 一个空生成器而不是默认情况下什么都没有。
def foo(l):
for elem in l:
yield elem
x = foo([]) # <generator object foo at 0x7f7393a0ae58>
这到底是如何工作的?
来自文档 (https://docs.python.org/3/reference/expressions.html#yield-expressions)
Using a yield expression in a function’s body causes that function to
be a generator.
也许你的意思是 yield elem
而不是 yield l
?
def foo(l):
for elem in l:
yield elem
for t in foo([1,2,3]):
print(t)
1
2
3
似乎如果函数体中的任何地方至少有一个 yield,那么即使没有达到 yield,它也会 return 一个空生成器而不是默认情况下什么都没有。
def foo(l):
for elem in l:
yield elem
x = foo([]) # <generator object foo at 0x7f7393a0ae58>
这到底是如何工作的?
来自文档 (https://docs.python.org/3/reference/expressions.html#yield-expressions)
Using a yield expression in a function’s body causes that function to be a generator.
也许你的意思是 yield elem
而不是 yield l
?
def foo(l):
for elem in l:
yield elem
for t in foo([1,2,3]):
print(t)
1
2
3