Python 具有两个内部函数的闭包
我试图写一个包含两个内部函数的闭包,但是我得到了下面的错误Python 具有两个内部函数的闭包,python,closures,Python,Closures,我试图写一个包含两个内部函数的闭包,但是我得到了下面的错误 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_cu
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
我是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
。如果没有非本地
,您将无法修改n
,但会得到:
UnboundLocalError: local variable 'n' referenced before assignment
因为n
只是一个局部变量非局部n
使内部函数内部可修改封闭函数中的n
。在current
中评估n
是可以的,因为Python的作用域规则允许从封闭函数的作用域读取外部作用域中的变量
嗨,迈克,我觉得非本地没有任何意义,我在给
在我的案例中有效的解决方案
Mike的非局部用法非常好,但我们也可以通过计数器内部函数中的新变量m从封闭范围访问变量n的值,并在递增后返回。这样,就不需要非局部
def factory(n=0):
def current():
return n
def counter():
m=n
m=m+1
return m
return current,counter
f_current,f_counter=factory(int(input()))
print(f_current())
print(f_counter())
`这个问题与标题无关。您希望
f\u current,f\u counter=int(input())
做什么?显式地将输入设为数字,然后尝试从数字中提取两个值。然后你试着把提取出来的数字作为函数调用,最后一行缺少一个大括号。这太宽泛了;这里的错误太多了。f_current
与factory(n)
有什么关系?很确定你的缩进在什么地方,但我不太确定你的意图在哪里。您的意思是返回当前值,count
?另外,我认为您不是要定义嵌套函数的输入参数,因为您谈到了闭包。看看LEGB和非本地
关键字。谢谢你,迈克。。。你能告诉我非局部是什么意思吗?nonlocal
name是周围函数的局部名称。需要声明来重新绑定周围函数范围中的名称。current
函数不需要声明,因为它只读取n
,不分配给n
。(这个关键词可能看起来很奇怪,但经过数月的争论,这个选择推迟了添加选项的时间。)如果你解释一下你提供的代码是如何回答这个问题的,这将是一个更好的答案。
def factory(n):
def current():
return n
def counter():
n=int(current())
n=n+1
return n
return current, counter
n=0
f_current, f_counter = factory((input()))
print(f_current())
print(f_counter())
def factory(n=0):
def current():
return n
def counter():
return n+1
return current, counter
f_current, f_counter = factory(int(input()))
print(f_current())
print(f_counter())
def factory(n=0):
def current():
return n
def counter():
m=n
m=m+1
return m
return current,counter
f_current,f_counter=factory(int(input()))
print(f_current())
print(f_counter())