2017-01-21 104 views
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 

谁能请解释一下吗?

回答

3

如果你使用Python 3(和它看起来像你的),有一个惊人的方式来解决这一问题:

def function(): 
    i = 0 
    def another_function(): 
     nonlocal i 
     # use 'i' here 

这里,i不是全局,因为它会被定义已经外两种功能否则。它也不在another_function之内,因为它在其外部定义。所以,它是非本地

更多信息有关nonlocal

+0

为什么'nonlocal'在所有必要的吗?即使在你的例子中,这只是一个闭包,意味着内函数_has_访问外函数中定义的变量。 –

+0

编辑:这是导致引用错误的'i + = 1'行,但无论如何,即使对于给定的代码重复调用,'i'也永远不会增加,'i'仍然可以通过闭包的范围访问。 –

+1

@Vincenzzzochi“我”的价值递增和使用非地方它完美的作品。 – n33rma

相关问题