函数python3里面的范围函数?

时间:2014-02-23 14:23:02

标签: python scope

当我在阅读关于命名空间和scthon的python时,我读到了

-the innermost scope, which is searched first, contains the local names
-the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
-the next-to-last scope contains the current module’s global names
-the outermost scope (searched last) is the namespace containing built-in names

但是当我尝试这个时:

def test() :
    name = 'karim'

    def tata() :
        print(name)
        name='zaka'
        print(name)
    tata()

我收到了这个错误:

UnboundLocalError: local variable 'name' referenced before assignment

当语句打印(名称)时,tata()函数在当前范围内找不到名称,因此python会在范围内找到并在test()函数范围内找到它吗? / p>

1 个答案:

答案 0 :(得分:0)

在python 3中,您可以使用nonlocal name告诉python name未在本地范围内定义,它应该在外部范围内查找它。

这有效:

def tata():
    nonlocal name
    print(name)
    name='zaka'
    print(name)