在闭包的情况下,为什么要使用两个括号?



我正在用一本书研究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.

因为countdown函数中有一个函数是count的,而且,当你返回count方法时,你不添加括号,这就是为什么你需要这样做。

它将返回:

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

如果打印c.

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

最新更新