2013-05-06 40 views
3

我不知道,爲什麼我的​​或NameError: global name 'i' is not defined在下面的代碼中的錯誤:在Python內部方法 - 無法訪問變量

def method1(): 
    i = 0 
    def _method1(): 
    # global i -- the same error 
    i += 1 
    print 'i=', i 

    # i = 0 -- the same error 
    _method1() 

method1() 

如何擺脫它? i不應該在py2x做到這一點method1()

回答

3

一種方法外部可見的是變量本身傳遞給內部方法,在py3x 這已被固定,你可以使用nonlocal聲明那裏。爲儘快提出

的錯誤,因爲函數是對象也和他們的定義過程中進行評估,並定義期間Python看到i += 1(這相當於i = i + 1),它認爲i是函數中的局部變量。但是,當實際調用該函數時,它無法在本地找到i(在RHS上)的任何值,從而導致錯誤發生。

def method1(): 
    i = 0 
    def _method1(i): 
    i += 1 
    print 'i=', i 
    return i  #return the updated value 

    i=_method1(i) #update i 
    print i 

method1() 

,或者使用功能屬性:

def method1(): 
    method1.i = 0  #create a function attribute 
    def _method1(): 
    method1.i += 1 
    print 'i=', method1.i 

    _method1() 

method1() 

對於py3x:

def method1(): 
    i =0 
    def _method1(): 
    nonlocal i 
    i += 1 
    print ('i=', i) 
    _method1() 

method1() 
+3

你可能想提一提,他/她正試圖創建一個閉包,以及如何在Python的實現。 – HennyH 2013-05-06 09:30:14