2013-11-14 72 views
4
def blah(self, args): 
    def do_blah(): 
     if not args: 
      args = ['blah'] 
     for arg in args: 
      print arg 

上述錯誤提示if not args表示UnboundLocalError:分配前引用的局部變量'args'。Python UnboundLocalError

def blah(self, args): 
    def do_blah(): 
     for arg in args:  <-- args here 
      print arg 

但這個作品儘管使用args

爲什麼不if not args:使用嗒嗒的ARGS的第一個?

+0

http://eli.thegreenplace.net/2011/05/15/understanding-unboundlocalerror-in-python/ – lucasg

+0

可能複製[傳遞從父功能參數嵌套函數的Python(http://stackoverflow.com/q/14678434)和[在Python封閉?(http://stackoverflow.com/q18274051) –

回答

3

問題是,當python在一個函數內部看到一個賦值,那麼它將該變量視爲局部變量,並且在執行該函數時不會從封閉或全局範圍中獲取其值。

args = ['blah'] 

foo = 'bar' 
def func(): 
    print foo #This is not going to print 'bar' 
    foo = 'spam' #Assignment here, so the previous line is going to raise an error. 
    print foo 
func()  

輸出:

File "/home/monty/py/so.py", line 6, in <module> 
    func() 
    File "/home/monty/py/so.py", line 3, in func 
    print foo 
UnboundLocalError: local variable 'foo' referenced before assignment 

注意,如果foo這裏是一個可變對象,並嘗試對其執行就地操作,則蟒是不會爲此抱怨。

foo = [] 
def func(): 
    print foo 
    foo.append(1) 
    print foo 
func() 

輸出:

[] 
[1] 

文檔:Why am I getting an UnboundLocalError when the variable has a value?

+0

很大。謝謝 – ealeon