我试图用两个内部函数编写一个闭包,但我收到以下错误
def factory(n=0):
#n=0
def current():
return n
return current
def counter():
n=n+1
return n
return counter
f_current,f_counter = int(input())
print(f_counter())
print(f_current())
我有以下错误:
>>4
Traceback (most recent call last):
File "C:/Users/lokesh/Desktop/python/closure3.py",
line 13, in <module>
f_current,f_counter = int(input())
TypeError: 'int' object is not iterable
我的要求是在给出输入4之后,它应该显示:
4
5
我是python的新手,有人可以帮助我......提前感谢
看起来更像你想要的东西:
def factory(n=0):
def current():
return n
def counter():
nonlocal n
n += 1
return n
return current, counter
f_current, f_counter = factory()
print(f_current())
print(f_counter())
print(f_current())
print(f_counter())
输出:
0
1
1
2
以4
为输入:
f_current, f_counter = factory(4)
print(f_current())
print(f_counter())
4
5
factory()
返回两个内部函数。您需要使用nonlocal
来增加封闭函数的n
。没有nonlocal
你将无法修改n
但会得到:
UnboundLocalError: local variable 'n' referenced before assignment
因为n
只是一个局部变量。 nonlocal n
从内部函数内部可修改的封闭函数中生成n
。在n
中评估current
很好,因为Python的作用域规则允许从外部作用域读取变量,这是从封闭函数的范围。