2016-01-23 11 views
0
>>> def bar(): 
     abc = 0 
     def run(): 
      global abc 
      abc += 1 
      print abc 
     return run 

>>> ccc = bar() 
>>> ccc() 

Traceback (most recent call last): 
    File "<pyshell#52>", line 1, in <module> 
    ccc() 
    File "<pyshell#50>", line 5, in run 
    abc += 1 
NameError: global name 'abc' is not defined 

如代碼中所示,變量'abc'在函數'bar'中定義,'bar'中定義的函數想要訪問'abc',我試圖在使用前使用全局聲明,但似乎是內部函數'運行'只在最外層的名字空間中搜索'abc'。那麼,如何在函數'run'中訪問'abc'?如何在函數功能情況下訪問外函數中定義的變量?

回答

1

如果您正在使用3.x中,你可以使用 「非本地ABC」,而不是 「全球ABC」

def bar(): 
    abc = 0 
    def run(): 
     nonlocal abc 
     abc += 1 
     print (abc) 
    return run 

在2.x中您可以使用下面的風格

def bar(): 
    abc = 0 
    def run(abc=abc): 
     abc += 1 
     print abc 
    return run 
+0

感謝您回答,在2.x中,def run(abc = abc),這裏abc是按值傳遞的,當調用run時,abc值不能每次都改變。只取值0並加1,但不能存回初始abc – yuyan

相關問題