2014-09-28 141 views
3

我想獲得某種確認上傳是成功的,我有我的方法定義類似於以下內容。但是全局變量的值沒有變化。請幫助python如何更改全局變量

global upload_confirm 
upload_confirm = False 

def confirm_upload(): 
    upload_confirm = True 

def start_new_upload(): 
    confirm_upload() 
    while (upload_confirm != True): 
     print "waiting for upload to be true" 
     time.sleep(5) 
    if (upload_confirm == True): 
     print "start Upload" 

start_new_upload() 

回答

3

你可以試試這個:

def confirm_upload(): 
    global upload_confirm 
    upload_confirm = True 

因爲你是在局部範圍做upload_confirm = True,巨蟒把它當作一個局部變量。因此,您的全局變量保持不變。

+0

如果我只想讀一個全局變量,我可以跳過每個函數開始時的'global'聲明嗎? – SomethingSomething 2014-09-28 14:20:45

+1

是的,你可以做到。 – 2014-09-28 14:21:24

1

你需要把global聲明該範圍內要訪問全局變量,即:

upload_confirm = False 

def confirm_upload(): 
    global upload_confirm 
    upload_confirm = True 
0

global的說法應該是裏面的功能。

def confirm_upload(): 
    global upload_confirm 
    upload_confirm = True 

否則,upload_confirm = ..會創建一個局部變量。

1

confirm_upload()方法中試試這個。

def confirm_upload(): 
    global upload_confirm #Add this line 
    upload_confirm = True 

您需要將其聲明爲全局內部方法否則它將默認爲本地。