Discuss / Python / 对于x=plus和x=plus()还是有点混乱

对于x=plus和x=plus()还是有点混乱

Topic source

苏晨飞

#1 Created at ... [Delete] [Delete and Lock User]

def createCounter():

 def plus():

  n = 1

  while True:

   yield n

   n += 1

 x = plus()

 def counter():

  return next(x)

 return counter

哆侎索

#2 Created at ... [Delete] [Delete and Lock User]

请问为什么要定义counter函数而不能直接在creatcounter最后写return next(t)呢?

x=plus,调用了plus函数,但是没有执行函数内容,所以返回的是函数

x=plus(),调用里plus函数,并执行了函数代码,返回的是函数执行结果

苏晨飞

#4 Created at ... [Delete] [Delete and Lock User]

因为x是定义在counter()函数外面的

苏晨飞

#5 Created at ... [Delete] [Delete and Lock User]

哦哦原来是这样 谢谢大佬

@用户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

Reply