2013-07-02 32 views
0

下面Python的「全球性」回報「的名字沒有被定義」

def A():  
    print "in A" 

    def B(): 
     global x 
     x += 1 
     y += 1 
     print "in B" 

    x = 0 
    y = 0 
    print x, y      
    B() 
    print x, y 


if __name__ == '__main__':  
    A() 

的代碼,我得到了下面的輸出和錯誤

in A 
0 0 
NameError: global name 'x' is not defined 

什麼是使用全局的正確方法嗎?實際上,我試圖在子函數B中更改x並將其返回給A.還嘗試檢查非全局y,並查看外函數中發生了什麼。


得到它從Haidro

def A(): 

    print "in A" 

    def B(): 
     global x   
     x += 1 
     y = 1 
     print "in B" 

    global x 
    x = 0 
    y = 0 
    print x, y      
    B() 
    print x, y 
+0

你不應該完全清楚你要去哪裏,但是應該避免使用IMO'global'。 – NPE

+0

什麼是取代全球的最佳方式?作爲參數傳入? – twfx

+1

@twfx使用一個類。檢查我的答案:)(底部) – TerryA

回答

2

給出暗示你會希望把global xA()還有:

def A():  
    print "in A" 

    def B(): 
     global x 
     global y # Also, don't forget to globalise y! 
     x += 1 
     y += 1 
     print "in B" 
    global x 
    global y 
    x = 0 
    y = 0 
    print x, y      
    B() 
    print x, y 


if __name__ == '__main__':  
    A() 

你必須把global xA()因此它可以請訪問B()。但是,你還是要離開global xB()這樣你就不會得到一個UnboundLocalError: local variable 'x' referenced before assignment


你可能要重新考慮你的結構。也許使用一個類?

class MyClass(object): 
    def __init__(self): 
     self.x = 0 
     self.y = 0 

    def A(self): 
     print "in A" 
     print self.x, self.y  
     self.B() 
     print self.x, self.y 

    def B(self): 
     self.x += 1 
     self.y += 1 
     print "in B" 

me = MyClass() # Create an instance of the class 
me.A() 
me.B() 
print me.x, me.y 

這將返回:

in A 
0 0 
in B 
1 1 
in B 
2 2 
1

機會是你真的不希望使用全局變量。一般而言,它們只能在絕對必要時使用。我認爲這是你想要達到的目標:

def A():  
    print "in A" 
    x = 5 
    def B(x): 
     print "in B" 
     return x 

    print B(x) 


if __name__ == '__main__':  
    A()