def make_accumulator(init):
def accumulate(part):
init = init + part
return init
return accumulate
A = make_accumulator(1)
print A(2)
给我:-
Traceback (most recent call last):
File "make-accumulator.py", line 8, in <module>
print A(2)
File "make-accumulator.py", line 3, in accumulate
init = init + part
UnboundLocalError: local variable 'init' referenced before assignment
为什么init在内部不可见?你知道吗
由于在accumulate中声明了
init
,Python将其解释为本地的,因此在赋值之前引用它。(注意,我删除了init =
部分)。你知道吗我肯定不是这方面的专家,但从这些帖子中得到了提示:Here和Here。你知道吗
我想有人可以解释得更好。。。你知道吗
这是因为在解析内部函数的过程中,当Python看到赋值
init = init + part
时,它认为init
是一个局部变量,它只会在函数实际被调用时在局部范围内查找它。你知道吗要修复它,请将
init
作为参数添加到accumulate
,默认值为init
:读取:Why am I getting an UnboundLocalError when the variable has a value?
相关问题 更多 >
编程相关推荐