如何在函数内访问函数中的变量

时间:2017-01-21 14:05:05

标签: python

我正在尝试在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”的声明时

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

当我添加“global i”声明时

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

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:3)

如果你正在使用Python 3(它看起来像你),那么解决这个问题的方法很棒:

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

此处,i不是全局的,因为它将在两个函数之外定义。它在another_function之外也不是本地的,因为它在它之外定义。所以,它是非本地

有关nonlocal的更多信息: