2014-02-23 76 views
0

,而我是阅读有关的名字空间和蟒蛇scopping,我读了范围函数里面的函数python3?

-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 

时声明print(name) tata()函数在当前范围中找不到名称,所以python会在范围内并在test()函数范围内找到它没有?

回答

0

在Python 3中,您可以使用nonlocal name来告诉python name未在本地作用域中定义,它应该在外部作用域中查找它。

这工作:

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