1 val = 9
 2 def test(flag):
 3     if flag:
 4         val = 1
 5     else:
 6         print("test")
 7     return val
 8
 9 if __name__ == '__main__':
10     ret = test(0)
11     print(ret)

运行如下:

linux@linux-desktop:~$ python3.3 test.py
fuck
Traceback (most recent call last):
File "test.py", line 10, in <module>
ret = test(0)
File "test.py", line 7, in test
return val
UnboundLocalError: local variable 'val' referenced before assignment

解释如下:

1.意思

本地变量xxx引用前没定义。

2.错误原因:

    在于python没有变量的声明 , 所以它通过一个简单的规则找出变量的范围 :如果有一个函数内部的变量赋值 ,该变量被认为是本地的,所以如果有修改变量的值就会变成局部变量。

3.解决方法:用global关键字来进行说明该变量是全局变量
python代码:
val=9
def test(flag):
    global val
    if flag: 
        val = 1 
    else: 
        print(test) 
    return val

本地变量xxx引用前没定义。

项目中遇到错误如下:

root@UA4300D-spa:~/hanhuakai/pro_07/0703/webview# python3 app.py
ERROR:tornado.application:Uncaught exception GET /top (192.168.2.144)
HTTPRequest(protocol='http', host='192.168.5.41:7777', method='GET', uri='/top', version='HTTP/1.1', remote_ip='192.168.2.144', headers={'Accept-Language': 'zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3', 'Accept-Encoding': 'gzip, deflate', 'Host': '192.168.5.41:7777', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0 (Windows NT 5.1; rv:30.0) Gecko/20100101 Firefox/30.0', 'Connection': 'keep-alive', 'Referer': 'http://192.168.5.41:7777/', 'Cache-Control': 'max-age=0', 'If-None-Match': '"56b2971f04441fe9644324362487e88a84a776de"'})
Traceback (most recent call last):
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 1218, in _when_complete
callback()
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 1239, in _execute_method
self._when_complete(method(*self.path_args, **self.path_kwargs),
File "app.py", line 21, in get
self.render("top.htm")
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 615, in render
html = self.render_string(template_name, **kwargs)
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 722, in render_string
return t.generate(**namespace)
File "/usr/lib/python3.2/site-packages/tornado/template.py", line 278, in generate
return execute()
File "top_htm.generated.py", line 5, in _tt_execute
_tt_tmp = _tt_modules.Workstate() # top.htm:34
File "/usr/lib/python3.2/site-packages/tornado/web.py", line 1313, in render
rendered = self._active_modules[name].render(*args, **kwargs)
File "app.py", line 2043, in render
info = s.faultyinfo()
File "/usr/lib/python3.2/xmlrpc/client.py", line 1076, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python3.2/xmlrpc/client.py", line 1403, in __request
verbose=self.__verbose
File "/usr/lib/python3.2/xmlrpc/client.py", line 1117, in request
return self.single_request(host, handler, request_body, verbose)
File "/usr/lib/python3.2/xmlrpc/client.py", line 1132, in single_request
return self.parse_response(resp)
File "/usr/lib/python3.2/xmlrpc/client.py", line 1303, in parse_response
return u.close()
File "/usr/lib/python3.2/xmlrpc/client.py", line 648, in close
raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault 1: "<class 'UnboundLocalError'>:local variable 'str_problem_in' referenced before assignment FILENAME: /usr/lib/python3.2/site-packages/ssapi/fm/faultyinfo.py LINE: 912 NAME: print_status_record">
ERROR:tornado.access:500 GET /top (192.168.2.144) 413.94ms

部分代码如下:

  1 def print_status_record(srp, faulty_item):
  2     global fmadm_msghdl
  3     uurp = srp.uurec
  4     str_time = time.ctime(uurp[0].sec)
  5     faulty_item.time = str_time            #"TIME"
  6     faulty_item.event_id = uurp[0].uuid    #"EVENT-ID"
  7     faulty_item.msg_id = srp.msgid         #"MSG-ID"
  8     faulty_item.severity = srp.severity    #"SEVERITY"
  9
 10     faulty_item.host = srp.host.server          #"Host"
 11     if srp.host.domain :
 12         faulty_item.domain = srp.host.domain    #"Domain"
 13     else:
 14         faulty_item.domain = "None"
 15
 16     faulty_item.platform = srp.host.platform    #"Platform"
 17     str_class_id = srp.host.chassis if srp.host.chassis else "None"
 18     str_product_sn = srp.host.product_sn if srp.host.product_sn else "None"
 19
 20     faulty_item.class_id = str_class_id         #"Chassis_id"
 21     faulty_item.product_sn = str_product_sn     #"Product_sn"
 22
 23     if srp.classt :                             #"Fault class"
 24         str_faulty_class = get_name_list(srp.classt, \
 25                 "Fault class :", srp.classt[0].pct, None)
 26         faulty_item.faulty_class = str_faulty_class
 27     else:
 28         faulty_item.faulty_class = "None"
 29
 30     if srp.asru :                               #"Affects"
 31         status = asru_same_status(srp.asru)
 32         if status != -1 :
 33             msg_name_list = get_name_list(srp.asru,"Affects     :", 0, None)
 34             msg_asru_status = print_asru_status(status, "             ")
 35             str_affects = msg_name_list + msg_asru_status
 36         else:
 37             str_affects = get_name_list(srp.asru,"Affects     :", 0, \
 38                     print_asru_status)
 39         faulty_item.affects = str_affects
 40     else:
 41         faulty_item.affects = "None"
 42
 43     if not srp.fru or not srp.asru :            #"Problem in"
 44         if srp.resource :
 45             status = asru_same_status(srp.resource)
 46             if status != -1 :
 47                 msg_name_list = get_name_list(srp.resource, \
 48                         "Problem in  :", 0, None)
 49                 msg_rsrc_status = print_rsrc_status(status, "             ")
 50                 str_problem_in = msg_name_list + msg_rsrc_status
 51             else:
 52                 str_problem_in = get_name_list(srp.resource, \
 53                         "Problem in  :", 0, print_rsrc_status)
 54         faulty_item.problem_in = str_problem_in
 55     else:
 56         faulty_item.problem_in = "None"
 57
 58     if srp.fru :                                #"FRU"
 59         status = asru_same_status(srp.fru)
 60         if status != -1 :
 61             msg_name_list = get_name_list(srp.fru, "FRU         :", \
 62                     100 if srp.fru[0].pct == 100 else \
 63                     srp.fru[0].max_pct, None)
 64             msg_fru_status = print_fru_status(status, "             ")
 65             str_fru = msg_name_list + msg_fru_status
 66         else:
 67             str_fru = get_name_list(srp.fru, "FRU         :", 100 \
 68                     if srp.fru[0].pct == 100 else srp.fru[0].max_pct, \
 69                     print_fru_status)
 70         faulty_item.fru = str_fru
 71     else:
 72         faulty_item.fru = "None"
 73
 74     if srp.serial and not serial_in_fru(srp.fru, srp.serial) and \
 75             not serial_in_fru(srp.asru, srp.serial) :
 76         str_serial_id = get_name_list(srp.serial, "Serial ID.  :", 0, None)
 77         faulty_item.serial_id = str_serial_id
 78     else:
 79         faulty_item.serial_id = "None"          #"Serial ID"
 80
 81     nvl = srp.uurec[0].event
 82     _fmd_msg_getitem_nv = libfmd_msg.fmd_msg_getitem_nv
 83     _fmd_msg_getitem_nv.restype = c_char_p
 84
 85     description = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
 86             FMD_MSG_ITEM_DESC)
 87     faulty_item.description = description.decode('UTF-8')   #"Description"
 88
 89     response = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
 90             FMD_MSG_ITEM_RESPONSE)
 91     faulty_item.response = response.decode('UTF-8')         #"Response"
 92
 93     impact = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
 94             FMD_MSG_ITEM_IMPACT)
 95     faulty_item.impact = impact.decode('UTF-8')             #"Impact"
 96
 97     action = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
 98             FMD_MSG_ITEM_ACTION)
 99     faulty_item.action = action.decode('UTF-8')             #"Action"
100
101     return faulty_item

解析:

当if not srp.fru or not srp.asru成立,并且if srp.resource不成立时,这是便直接执行:faulty_item.problem_in = str_problem_in因此就会出现以上错误信息,值得注意!错误修改如下:
 1     if not srp.fru or not srp.asru :            #"Problem in"
 2         if srp.resource :
 3             status = asru_same_status(srp.resource)
 4             if status != -1 :
 5                 msg_name_list = get_name_list(srp.resource, \
 6                         "Problem in  :", 0, None)
 7                 msg_rsrc_status = print_rsrc_status(status, "             ")
 8                 str_problem_in = msg_name_list + msg_rsrc_status
 9             else:
10                 str_problem_in = get_name_list(srp.resource, \
11                         "Problem in  :", 0, print_rsrc_status)
12             faulty_item.problem_in = str_problem_in
13         else:
14             faulty_item.problem_in = "None"
15     else:
16         faulty_item.problem_in = "None"

 

转载于:https://www.cnblogs.com/fendou-999/p/3822028.html

python 错误--UnboundLocalError: local variable '**' referenced before assignment相关推荐

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

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

  2. UnboundLocalError: local variable referenced before assignment

    写笔记的第二天,另外希望自己能慢慢打动自己的女神누나 昨天,突然遇到了一个在函数内部修改全局变量却报错的问题,在网上查了下发现是经典问题,记一下日后慢慢消化. 提醒自己,函数内部修改全局变量时要思考三 ...

  3. Python 引用全局变量提示:local variable referenced before assignment. 问题解决办法,global使用方法介绍

    local variable 'a' referenced before assignment 就是说变量a在使用前没有被声明 可能的情况一般有两种: 情况一:变量没有被赋值直接引用了 def hel ...

  4. Python 读写当前路径下文件错误 UnboundLocalError: local variable 'file' referenced before assignment

    python读取文件是个比较常用的操作,最近我在读取文件的时候却遇到下面这个问题. 我的代码是: try:file = open("./logs/test")... finally ...

  5. python UnboundLocalError: local variable 'log_f' referenced before assignment 错误

    在写一个python程序,用finally处理异常的时候,报了"UnboundLocalError: local variable 'log_f' referenced before ass ...

  6. UnboundLocalError: local variable ‘a‘ referenced before assignment(Python报错解决)

    问题提出 使用Python编程的时候,要注意函数内可以访问全局变量,但不能更新(修改)其值. 比如: a = 10 def sum ( n ) :n += aprint ('a = ', a, end ...

  7. 【debug】UnboundLocalError local variable a referenced before assignment

    1)下面这种情况是不会报错的: >>> x = 10 >>> def bar(): ... print(x) >>> bar() 10 (2)但是 ...

  8. UnboundLocalError: local variable ‘XXX‘ referenced before assignment解决办法

    一.举例: 计算a到10的和 sum=0 def func(a):while a<=10:sum+=aa+=1return sum print(func(9)) 运行结果: UnboundLoc ...

  9. UnboundLocalError: local variable 'end_page' referenced before assignment

    UnboundLocalError: local variable 'end_page' referenced before assignment 错误信息是在指出一个在使用之前没有赋值的局部变量.在 ...

最新文章

  1. 如何处理几十万条并发数据?
  2. 智能交通大数据及云应用平台解决方案
  3. bottle框架学习(八)之Mysql数据库的操作
  4. python【蓝桥杯vip练习题库】ADV-92求最大公约数(递归)
  5. Hive group by实现-就是word 统计
  6. 第二届战神杯线上编程挑战赛月赛第一题:回文数
  7. ASP.NET PipeLine #Reprinted#
  8. python建模分析实操_城市公交站点设置优化模型-基于Python
  9. PopStar(消灭星星)游戏源代码下载、分析及跨平台移植---第四篇(关卡)
  10. 【报告分享】2020中国数字化后浪:中小企业转型与创新实录.pdf(附下载链接)...
  11. XRDP与VNC的关系
  12. CCNP 640-892知识点中文精简解释
  13. 运用正则表达式在Asp中过滤Html标签代码的四种不同方法
  14. java分享微博_Connect/sharing - 微博API
  15. 我经常登录的GIS专业论坛
  16. 计算机考研需要分数线,计算机考研分数线是多少?
  17. 采用16线激光雷达和轮式里程计调用cartographer室内融合定位
  18. springboot毕设项目东莞汉庭酒店的酒店管理系统的设计与实现4ccnv(java+VUE+Mybatis+Maven+Mysql)
  19. 实验三+161+张丽霞
  20. Python基于OpenCV的指针式表盘检测系统(附带源码&技术文档)

热门文章

  1. CSS3--选择器、动画效果
  2. winform下载网页源码
  3. Docker namespace技术(九)
  4. C++中vector的capacity和size的区别
  5. 【UWP】使用 Rx 改善 AutoSuggestBox
  6. 在Python中使用正则表达式去掉字符串里的html标签
  7. vue-cli 自定义指令directive 添加验证滑块
  8. 数据科学家最常用的10种算法
  9. 并发,std::thread
  10. 启用邮箱提示访问特权不够