对于闭包,为什么要使用两个括号?

问题描述 投票:2回答:1

我正在用书研究Python闭包。我做了一个功能。该功能正在减少1.我不明白为什么要使用两个括号?当我使用分配的变量c时,返回值为函数。

n=int(input('enter c: '))
def countdown(n):


    def count():
        global n
        r=n
        n -= 1
        return r

    return count

c=countdown(n)

for i in range(n):
    print(c(),end=' ') # I don't understand why use c() not c.
python function closures
1个回答
2
投票

由于countdown函数中有一个函数count,并且,当您返回count方法时,您无需添加括号,这就是您需要这样做的原因。

它将返回:

<function countdown.<locals>.count at 0x00000007237F31E0>

如果打印c

[countdown(...)返回一个函数,该函数也需要调用。

© www.soinside.com 2019 - 2024. All rights reserved.