我正在用书研究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(...)
返回一个函数,该函数也需要调用。