2014-08-28 45 views
0

我一直在使用WinPython編碼,使用一個全局變量的程序,這是代碼:,這是正常的行爲嗎?

def main(): 
    global listC 
    listC=[1,2,3,4,5] 

def doSomething(): 
    if listC!=[]: 
     pass 

,我有這樣的問題,說如果listC = ...拋出我行!警告說「未定義名稱listC」;這個程序實際上編譯和執行正常,但我想知道爲什麼如果我已經聲明列表作爲一個全局變量的警告。

我想通過以下方式來執行它:

programName.main()  //init the list 
programName.doSomething() //do an operation with the list 
programName.doSomething()  //same as before 
... 

感謝

+0

我必須同意下面的jsbueno,在doSomething()中必須發生其他事情。你發佈的代碼工作正常。 – whitebeard 2014-08-28 01:48:57

回答

0

這應該是工作......這對我的作品。

def doSomething(): 
    if listC != []: 
     print "success!" 

def main(): 
    global listC 
    listC = [1,2,3,4,5] 
    doSomething() 

>>> main() 
success! 
+0

也是錯誤的。沒有這樣的需求 - 只要它在'main'中被聲明爲全局的並且代碼首先運行。 – jsbueno 2014-08-28 01:30:50

+0

@jsbueno當然!不知道我在想什麼......那完全正常......改變了我的答案...... – whitebeard 2014-08-28 01:37:50

1

隨着代碼的部分,你向我們展示,它應該工作 - 但是,因爲你得到的錯誤,這是怎麼回事是你在某個時刻作出的分配listCdoSomething函數的主體中。

如果有任何此類轉讓,Python將視listC變量作爲本地 到doSomething - 除非你把其列爲在函數的beggining全球 - 當然,你也必須把它宣佈爲全球在此函數中初始化它 - main,並確保初始化代碼在調用doSomething之前運行。

def main(): 
    global listC 
    listC=[1,2,3,4,5] 

def doSomething(): 
    global listC 
    if listC != []: 
     print "success!" 
    # the following statement would trigger a NameError above, if not for the "global": 
    listC = [2,3]