0
我想在Python3.4中运行以下代码,但出现错误。如何在函数内部访问函数中的变量
def checknumner():
i = 0
print("checknumber called...")
def is_even():
print("is_even called...")
global i
if i % 2 == 0:
print("Even: ", i)
else:
print("Odd: ", i)
i += 1
return is_even
c = checknumner()
print(c())
print(c())
print(c())
我无法在子函数中访问变量“i”。
当我注释掉 “全局I” statment
D:\Study\Python>python generator_without_generator.py checknumber called... is_even called... Traceback (most recent call last): File "generator_without_generator.py", line 24, in <module>
print(c()) File "generator_without_generator.py", line 16, in is_even
if i % 2 == 0: UnboundLocalError: local variable 'i' referenced before assignment
当我添加 “全局I” statment
D:\Study\Python>python generator_without_generator.py checknumber called... is_even called... Traceback (most recent call last): File "generator_without_generator.py", line 24, in <module>
print(c()) File "generator_without_generator.py", line 16, in is_even
if i % 2 == 0: NameError: name 'i' is not defined
谁能请解释一下吗?
为什么'nonlocal'在所有必要的吗?即使在你的例子中,这只是一个闭包,意味着内函数_has_访问外函数中定义的变量。 –
编辑:这是导致引用错误的'i + = 1'行,但无论如何,即使对于给定的代码重复调用,'i'也永远不会增加,'i'仍然可以通过闭包的范围访问。 –
@Vincenzzzochi“我”的价值递增和使用非地方它完美的作品。 – n33rma