2017-06-23 39 views
0

我是新來的Python,在此之前,我用的是C.的Python - 訪問全局列表功能

def cmplist(list): #Actually this function calls from another function 
    if (len(list) > len(globlist)): 
     globlist = list[:] #copy all element of list to globlist 

# main 
globlist = [1, 2, 3] 
lst = [1, 2, 3, 4] 
cmplist(lst) 
print globlist 

當我執行這個代碼,它顯示了以下錯誤

if (len(list) > len(globlist)): 
NameError: global name 'globlist' is not defined 

我想從函數訪問和修改globlist,而不用將其作爲參數傳遞。在這種情況下,輸出應該是

[1, 2, 3, 4] 

任何人都可以幫助我找到解決方案嗎?

總是歡迎任何建議和更正。 在此先感謝。

編輯: 感謝Martijn Pieters的建議。 原始誤差

UnboundLocalError: local variable 'globlist' referenced before assignment 
+0

你** **肯定認爲那就是拋出異常的代碼?因爲按照書面,你會得到'UnboundLocalError'。 –

+0

換句話說,你*不能*得到一個'NameError',這個名字在你發佈的示例代碼中有明確的定義。此外,您發佈的代碼將分配給函數*中的名稱'globlist' *,使其成爲本地代碼,除非用下面答案中所述的'global'語句特別覆蓋。但是,只有當你發佈的代碼有不同的例外時,這纔有意義。 –

+0

不便之處。是的,它顯示以下錯誤'UnboundLocalError:在分配前引用的局部變量'globlist' –

回答

4

你可以這樣做:

def cmplist(list): #Actually this function calls from another function 
    global globlist 
    if (len(list) > len(globlist)): 
     globlist = list[:] #copy all element of list to globlist 

這可能是更Python將它傳遞,雖然修改的方式。

+0

或者使用'globlist [:] = list'並放棄'global'關鍵字。但是,給出的例外表明瞭一個非常不同的問題。發佈的代碼和異常不匹配。 –

+0

謝謝,西蒙,它的工作原理。 –

0

您需要將其聲明爲全局的功能:

def cmplist(list): #Actually this function calls from another function 
    global globlist 
    if len(list) > len(globlist): 
     globlist = list[:] #copy all element of list to globlist 

# main 
globlist = [1, 2, 3] 
lst = [1, 2, 3, 4] 
cmplist(lst) 
print globlist 
0

內部功能cmplist,對象globlist'是不被認爲是全球範圍。 Python解釋器將其視爲局部變量;在函數cmplist中找不到它的定義。因此錯誤。 函數內部聲明全局列表在第一次使用之前是全局的。 像這樣的工作:

def cmplist(list): 
    global globlist 
    ... # Further references to globlist 

HTH, Swanand