关于 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。
---------------------
作者:jiangnanandi
来源:CSDN
原文:https://blog.csdn.net/jiangnanandi/article/details/3553243
版权声明:本文为博主原创文章,转载请附上博文链接!

This inspection warns about local variables referenced before assignment.的更多相关文章

  1. python 错误--UnboundLocalError: local variable '**' referenced before assignment

    val = 9 def test(flag): if flag: val = 1 else: print("test") return val if __name__ == '__ ...

  2. local variables referenced from a Lambda expression must be final or effectively final------理解

    前几天使用lamdba时,报了一个这个错,原因是在lamdba体中使用了一个变量,觉得很奇怪! 今天在读这本书的时候,又看到了这个解释,这里有了更深刻的理解,总结一下: 在jdk1.8之前在使用匿名内 ...

  3. Effective Java 45 Minimize the scope of local variables

    Principle The most powerful technique for minimizing the scope of a local variable is to declare it ...

  4. local variable 'xxx' referenced before assignment

    这个问题很囧,在外面定义了一个变量 xxx ,然后在python的一个函数或类里面引用这个变量,并改变它的值,结果报错local variable 'xxx' referenced before as ...

  5. Implicitly Typed Local Variables

    Implicitly Typed Local Variables It happens time and time again: I’ll be at a game jam, mentoring st ...

  6. 遇到local variable 'e' referenced before assignment这样的问题应该如何解决

    问题:程序报错:local variable 'e' referenced before assignment 解决:遇到这样的问题,说明你在声明变量e之前就已经对其进行了调用,定位到错误的地方,对变 ...

  7. RDO Stack Exception: UnboundLocalError: local variable 'logFile' referenced before assignment

    Issue: When you install RDO stack on CentOS, you may encounter following error. Error: [root@localho ...

  8. Python问题:UnboundLocalError: local variable 'xxx' referenced before assignment

    参考链接: http://blog.csdn.net/onlyanyz/article/details/45009697 https://www.cnblogs.com/fendou-999/p/38 ...

  9. 洗礼灵魂,修炼python(23)--自定义函数(4)—闭包进阶问题—>报错UnboundLocalError: local variable 'x' referenced before assignment

    闭包(lexical closure) 什么是闭包前面已经说过了,但是由于遗留问题,所以单独作为一个章节详解讲解下 不多说,看例子: def funx(x): def funy(y): return ...

随机推荐

  1. jquery+javascript触发a标签的点击事件

    今天项目经理跟我说window.open()在一些浏览器上会被拦截,当时的解决方案是:用a标签的target="_blank"属性也可以打开窗体页面 于是解决了A问题出现了B问题: ...

  2. 利用URL Protocol实现网页调用本地应用程序

    http://blog.csdn.net/zssureqh/article/details/25828683

  3. 转 jmeter 等待时间 pacing think time

    第一部分:Request之间的等待时间的设置 先明确一些概念:1)定时器是在每个sampler(采样器)之前执行的,而不是之后:是的,你没有看错,不管这个定时器的位置放在sampler之后,还是之下, ...

  4. mybatis之增删改

    前面三小节内容主要是针对查询操作进行讲解,现在对mybatis增删改进行演示. 由于每次建立工程比较复杂,可以参考第一节:mybatis入门来搭建一个简单的工程,然后来测试本节内容. 1.增 1.新增 ...

  5. 轻松理解https,So easy!

    Java技术栈 www.javastack.cn 优秀的Java技术公众号 作者:翟志军 https://showme.codes/2017-02-20/understand-https/ 本文尝试一 ...

  6. SQL中to_char方法的应用

    1.取得当前日期是本月的第几周 SQL> select to_char(sysdate,'YYYYMMDD W HH24:MI:SS') from dual; ----------------- ...

  7. 在同一个项目中灵活运用application/json 和application/x-www-form-urlencoded 两种传输格式(配合axios,同时配置loading)

    'use strict' import axios from 'axios' // import qs from 'qs' import { Notification} from 'element-u ...

  8. vue 中引入cryptoJS

    在搞前端开发的时候,页面上有很多的地方是需要用户输入信息的,但是有些信息又很敏感,比如客户的姓名.电话号码.身份证号码.银行卡号及密码等等这些,如果没有进行加密处理,很容易被别人截取到,项目中应用到c ...

  9. react 16.3+ 新生命周期

    react 16.3版本出现了两个新的生命周期函数,并将逐渐废弃componentWillMount().componentWillReceiveProps().componentWillUpdate ...

  10. 2018-8-29-Roslyn-静态分析

    title author date CreateTime categories Roslyn 静态分析 lindexi 2018-08-29 09:10:19 +0800 2018-03-13 14: ...