对于x=plus和x=plus()还是有点混乱
Topic source@用户9229373643
x=plus()没有问题的。此处x=plus()只是生成了一个引用,并没有实际执行。
plus是生成器时的x=plus(),等于当plus为普通函数时的x=plus。
测试代码如下:
# 对于序列生成器来说,调用只是生成一个序列生成器,实际的执行,通过next()方法
def testYield():
num=1
while True:
print("call " + str(num))
yield num
num+=1
a = testYield()
print("before call")
next(a)
输出:
before call
call 1
- 1
苏晨飞
def createCounter():
def plus():
n = 1
while True:
yield n
n += 1
x = plus()
def counter():
return next(x)
return counter