1. 程式人生 > >關於 local variable 'has' referenced before assignment 問題

關於 local variable 'has' referenced before assignment 問題

  今天在django開發時,訪問頁面總是出現錯誤提示“
local variable 'has' referenced before assignment
”,查了一下資料,好像是說無法訪問這個變數,檢查一下程式碼我的檢視是這樣寫的:

def MusicTable(request):
    MUSICIANS = [ 
        {'name': 'Django Reinhardt', 'genre': 'jazz'}, 
        {'name': 'Jimi Hendrix',     'genre': 'rock'}, 
        {'name': 'Louis Armstrong',  'genre': 'jazz'}, 
        {'name': 'Pete Townsend',    'genre': 'rock'}, 
        {'name': 'Yanni',            'genre': 'new age'}, 
        {'name': 'Ella Fitzgerald',  'genre': 'jazz'}, 
        {'name': 'Wesley Willis',    'genre': 'casio'}, 
        {'name': 'John Lennon',      'genre': 'rock'}, 
       {'name': 'Bono',             'genre': 'rock'}, 
       {'name': 'Garth Brooks',     'genre': 'country'}, 
       {'name': 'Duke Ellington',   'genre': 'jazz'}, 
       {'name': 'William Shatner',  'genre': 'spoken word'}, 
       {'name': 'Madonna',          'genre': 'pop'},]
    Mu=[]
    #預處理 判斷是否粗體顯示 ,模板只是呈現方式,不應該處理 判斷哪些是特殊顯示
    for m in MUSICIANS:
        if '' not in m['name']:

             has = True
        Mu.append({'name':m['name'],
                   'genre':m['genre'],
                   'is_important':m['genre'] in ('jazz','rock'),
                   'is_pretentious': ' ' not in  m['name'],}
                  )
    return render_to_response('Musictable.html', {'Mu': Mu,'has_pretentious':has,})

    猛地一看變數has應該是有賦值啊,我鬱悶了。
    後來看到網上一個帖子說的也是這個問題
-------------------------------------------------------------------------------

程式大致是這樣的:

CONSTANT = 0


def modifyConstant() :
        print CONSTANT
        CONSTANT += 1
        return

if __name__ == '__main__' :
        modifyConstant()
        print CONSTANT

執行結果如下:
UnboundLocalError: local variable 'CONSTANT' referenced before assignment

看來,全域性變數在函式modifyConstant中邊成了區域性變數,似乎全域性變數沒有生效?
做點修改:

CONSTANT = 0

def modifyConstant() :

        print CONSTANT
        #CONSTANT += 1
        return

if __name__ == '__main__' :
        modifyConstant()
        print CONSTANT

執行正常,看來函式內部是可以訪問全域性變數的。
所以,問題就在於,因為在函式內部修改了變數CONSTANT,Python認為CONSTANT是區域性變數,而print CONSTANT又在CONSTANT += 1之前,所以當然會發生這種錯誤。

那麼,應該如何在函式內部訪問並修改全域性變數呢?應該使用關鍵字global來修飾變數(有點像PHP):

CONSTANT = 0

def modifyConstant() :
        global CONSTANT
        print CONSTANT
        CONSTANT += 1
        return

if __name__ == '__main__' :
        modifyConstant()
        print CONSTANT

就這麼簡單!

------------------------------------------------------------------------------------
看了上邊帖子內容,我有了一點啟發,仔細看一下我程式這裡:
for m in MUSICIANS:
        if '' not in m['name']:
             has = True
        Mu.append({'name':m['name'],
                   'genre':m['genre'],
                   'is_important':m['genre'] in ('jazz','rock'),
                   'is_pretentious': ' ' not in  m['name'],}
                  )
    return render_to_response('Musictable.html', {'Mu': Mu,'has_pretentious':has,})

標紅的部分 ''中間沒有空格,而在這個迴圈中根本沒有一次能滿足if '' not in m['name']: 這個條件,所以在 return render_to_response('Musictable.html', {'Mu': Mu,'has_pretentious':has,}) 傳遞 has的時候,報錯。
解決辦法有兩個 一個是將if '' not in m['name']: 的''加上空格變成‘ ’。
第二個辦法在之前給has一個初始值 has=False。

相關推薦

關於 local variable 'has' referenced before assignment 問題

  今天在django開發時,訪問頁面總是出現錯誤提示“local variable 'has' referenced before assignment”,查了一下資料,好像是說無法訪問這個變數,檢查一下程式碼我的檢視是這樣寫的:def MusicTable(request

常見的local variable 'x' referenced before assignment問題

def fun1(): x = 5 def fun2(): x *= 2 return x return fun2()如上程式碼,呼叫fun1() 執行會出錯:UnboundLocalError: local vari

python使用textract解析pdf時遇到UnboundLocalError: local variable 'pipe' referenced before assignment

工作需要要用python解析各種文件,我敬愛的manager AKA Byrd推薦給了我textract。“Textract is the most ridiculous library that I've ever used before”,其實它還是挺強大的,只是對於pd

全域性變數報錯:UnboundLocalError: local variable 'l' referenced before assignment

全域性變數報錯:UnboundLocalError: local variable ‘j’ referenced before assignment 最近在自學python,遇見以下問題:

UnboundLocalError: local variable 'XXX' referenced before assignment

這個問題很囧,在外面定義了一個變數 xxx ,然後在python的一個函式裡面引用這個變數,並改變它的值,結果報錯local variable 'xxx' referenced before assignment,程式碼如下: xxx = 23 def Print

全局變量報錯:UnboundLocalError: local variable 'l' referenced before assignment

使用 sign oot .net sam 單獨 規則 spa 兩個 總結: 內部函數,不修改全局變量可以訪問全局變量 內部函數,修改同名全局變量,則python會認為它是一個局部變量 在內部函數修改同名全局變量之前調用變量名稱(如print sum),則引發Unb

Python-local variable 'raw_password' referenced before assignment

str 分支 true 解決 OS 得到 __name__ -s 作用 where?   執行Python程序的時候,報這個錯 why?   變量作用域問題,在分支中定義的變量,當滿足條件的時候則可以正確得到變量,當不滿足條件的時候則報這個錯 way?   把變量從分支中抽

關於local variable 'i' referenced before assignment

如題,執行程式碼如下: def createCounter(): i = 0 def counter(): i+=1 j = i return j return counter 程式碼執行後出錯,錯誤資訊為:lo

python UnboundLocalError: local variable 'xxx' referenced before assignment

大意就是在變數定義前就引用了變數。 錯誤程式碼如下: def f(): print(n) n = 10 f() 這裡還是很清楚,很明白。 然而下面的程式碼就令人有些頭疼: n = 100 def f(): print(n) n = 10 f()

JSP 使用<%@include%>報Duplicate local variable path 錯誤 解決方法

錯誤提示 cat not 情況 cal quest epon bsp multi 錯誤提示:Multiple annotations found at this line:- Duplicate local variable path- Duplicate local va

java9 Local-variable type inference

ont java white b- lis var span ray pac var ls = Arrays.asList("1","2"); System.out.println(ls);java9 Local-variable type inference

java Error---Lambda expression's local variable e cannot re-declare another local variable defined e

在使用lambda表示式時,為控制元件新增事件響應函式時,出現: Lambda expression's local variable e cannot re-declare another local variable defined e 出錯的程式碼段如下: stage

Unity報錯:The variable ... has not been assigned.

Unity報錯:The variable prg of Rg02 has not been assigned. The variable prg of Rg02 has not been assigned. using System.Collections; using System.Col

Ask HN: When has big $$$ before product

The push toward PMF has been really great for the industry and really helped avoid wasting a ton of cash.The only argument AGAINST it rally is when a team

Eclipse快捷鍵Assign to local variable

當你new Object()寫完之後是不是又跑到行首寫Object object = ,是不是感覺既費力又2呢= = Window----Preferences----Keys----更改完之後(你也

JSP 使用報Duplicate local variable path 錯誤 解決方法

錯誤提示: Multiple annotations found at this line:  - Duplicate local variable path  - Duplicate local variable   basePath 重複變數, 因為<%@include%>引進的是程式碼,

The local variable date may not have been initialized解決辦法

這個錯誤的出現原因是我們沒有對變數輔助,也就是說如果我們隊我們所定義的變數複製之後,這個錯誤就會消失,比如 SimpleDateFormat simpleDateFormat = new Simple

FINDBUGS錯誤:Deadstore to local variable

FINDBUGS錯誤:Deadstore to local variable原因 原始碼: Map map =new HashMap(); map = UdeclareUtil.getPageList(yae258,"ap11List"); FINDBUGS錯誤:本地儲存了多

findbugs中Dead store to local variable [DLS_DEAD_LOCAL_STORE]

 List<BY102010ResultDetailModel> detailList = new ArrayList(); detailList = resultModel.getDetails(); 用findbugs執行後,說List<BY10

Unity3d中UnassignedReferenceException: The variable target of Moving has not been assigned. You proba

  在unity中出現 UnassignedReferenceException: The variable target of Moving has not been assigned. You probably need to assign the target var