2014-02-23 117 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)