python 错误--UnboundLocalError: local variable '**' referenced before assignment
val = 9
def test(flag):
if flag:
val = 1
else:
print("test")
return val if __name__ == '__main__':
ret = test(0)
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
部分代码如下:
def print_status_record(srp, faulty_item):
global fmadm_msghdl
uurp = srp.uurec
str_time = time.ctime(uurp[0].sec)
faulty_item.time = str_time #"TIME"
faulty_item.event_id = uurp[0].uuid #"EVENT-ID"
faulty_item.msg_id = srp.msgid #"MSG-ID"
faulty_item.severity = srp.severity #"SEVERITY" faulty_item.host = srp.host.server #"Host"
if srp.host.domain :
faulty_item.domain = srp.host.domain #"Domain"
else:
faulty_item.domain = "None" faulty_item.platform = srp.host.platform #"Platform"
str_class_id = srp.host.chassis if srp.host.chassis else "None"
str_product_sn = srp.host.product_sn if srp.host.product_sn else "None" faulty_item.class_id = str_class_id #"Chassis_id"
faulty_item.product_sn = str_product_sn #"Product_sn" if srp.classt : #"Fault class"
str_faulty_class = get_name_list(srp.classt, \
"Fault class :", srp.classt[0].pct, None)
faulty_item.faulty_class = str_faulty_class
else:
faulty_item.faulty_class = "None" if srp.asru : #"Affects"
status = asru_same_status(srp.asru)
if status != -1 :
msg_name_list = get_name_list(srp.asru,"Affects :", 0, None)
msg_asru_status = print_asru_status(status, " ")
str_affects = msg_name_list + msg_asru_status
else:
str_affects = get_name_list(srp.asru,"Affects :", 0, \
print_asru_status)
faulty_item.affects = str_affects
else:
faulty_item.affects = "None" if not srp.fru or not srp.asru : #"Problem in"
if srp.resource :
status = asru_same_status(srp.resource)
if status != -1 :
msg_name_list = get_name_list(srp.resource, \
"Problem in :", 0, None)
msg_rsrc_status = print_rsrc_status(status, " ")
str_problem_in = msg_name_list + msg_rsrc_status
else:
str_problem_in = get_name_list(srp.resource, \
"Problem in :", 0, print_rsrc_status)
faulty_item.problem_in = str_problem_in
else:
faulty_item.problem_in = "None" if srp.fru : #"FRU"
status = asru_same_status(srp.fru)
if status != -1 :
msg_name_list = get_name_list(srp.fru, "FRU :", \
100 if srp.fru[0].pct == 100 else \
srp.fru[0].max_pct, None)
msg_fru_status = print_fru_status(status, " ")
str_fru = msg_name_list + msg_fru_status
else:
str_fru = get_name_list(srp.fru, "FRU :", 100 \
if srp.fru[0].pct == 100 else srp.fru[0].max_pct, \
print_fru_status)
faulty_item.fru = str_fru
else:
faulty_item.fru = "None" if srp.serial and not serial_in_fru(srp.fru, srp.serial) and \
not serial_in_fru(srp.asru, srp.serial) :
str_serial_id = get_name_list(srp.serial, "Serial ID. :", 0, None)
faulty_item.serial_id = str_serial_id
else:
faulty_item.serial_id = "None" #"Serial ID" nvl = srp.uurec[0].event
_fmd_msg_getitem_nv = libfmd_msg.fmd_msg_getitem_nv
_fmd_msg_getitem_nv.restype = c_char_p description = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
FMD_MSG_ITEM_DESC)
faulty_item.description = description.decode('UTF-8') #"Description" response = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
FMD_MSG_ITEM_RESPONSE)
faulty_item.response = response.decode('UTF-8') #"Response" impact = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
FMD_MSG_ITEM_IMPACT)
faulty_item.impact = impact.decode('UTF-8') #"Impact" action = _fmd_msg_getitem_nv(fmadm_msghdl, None, nvl, \
FMD_MSG_ITEM_ACTION)
faulty_item.action = action.decode('UTF-8') #"Action" return faulty_item
解析:
当if not srp.fru or not srp.asru成立,并且if srp.resource不成立时,这是便直接执行:faulty_item.problem_in = str_problem_in
因此就会出现以上错误信息,值得注意!
错误修改如下:
if not srp.fru or not srp.asru : #"Problem in"
if srp.resource :
status = asru_same_status(srp.resource)
if status != -1 :
msg_name_list = get_name_list(srp.resource, \
"Problem in :", 0, None)
msg_rsrc_status = print_rsrc_status(status, " ")
str_problem_in = msg_name_list + msg_rsrc_status
else:
str_problem_in = get_name_list(srp.resource, \
"Problem in :", 0, print_rsrc_status)
12 faulty_item.problem_in = str_problem_in
13 else:
14 faulty_item.problem_in = "None"
else:
faulty_item.problem_in = "None"
python 错误--UnboundLocalError: local variable '**' referenced before assignment的更多相关文章
- _markupbase.py if not match: UnboundLocalError: local variable 'match' referenced before assignment,分析Python 库 html.parser 中存在的一个解析BUG
BUG触发时的完整报错内容(本地无关路径用已经用 **** 隐去): **************\lib\site-packages\bs4\builder\_htmlparser.py:78: U ...
- 洗礼灵魂,修炼python(23)--自定义函数(4)—闭包进阶问题—>报错UnboundLocalError: local variable 'x' referenced before assignment
闭包(lexical closure) 什么是闭包前面已经说过了,但是由于遗留问题,所以单独作为一个章节详解讲解下 不多说,看例子: def funx(x): def funy(y): return ...
- 变量引用的错误:UnboundLocalError: local variable 'range' referenced before assignment
class Battery(): """一次模拟电瓶汽车的简单尝试""" def __init__(self,battery_size = ...
- UnboundLocalError: local variable 'range' referenced before assignment
1. 报错信息 UnboundLocalError: local variable 'range' referenced before assignment 2. 代码 class Car(): &q ...
- 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 ...
- 出现UnboundLocalError: local variable 'a' referenced before assignment异常的情况与解决方法
出现UnboundLocalError: local variable ‘a’ referenced before assignment异常的情况与解决方法字面意思:局部变量赋值前被引用原因:局部变量 ...
- This inspection warns about local variables referenced before assignment.
关于 local variable 'has' referenced before assignment 问题 今天在django开发时,访问页面总是出现错误提示“local variable 'ha ...
- jsp的<%@ include file="jsp/common.jsp" %>报错误Duplicate local variable basePath
将公共引入的文件放到common.jsp中,其他页面引入该jsp即可使用 <%@ page language="java" import="java.util.*& ...
- UnboundLocalError: local variable 'foo' referenced before assignment Python常见错误
在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在) 在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的, 使用规则:如果在函数中定义了任何东西,如果它只是在函数中使用 ...
随机推荐
- 洛谷P3959 宝藏(NOIP2017)(状压DP,子集DP)
洛谷题目传送门 Dalao的题解多数是什么模拟退火.DFS剪枝.\(O(3^nn^2)\)的状压DP之类.蒟蒻尝试着把状压改进了一下使复杂度降到\(O(3^nn)\). 考虑到每条边的贡献跟它所在的层 ...
- luogu4932 浏览器 (拆)
分析1的个数的奇偶性: 奇xor奇=偶xor偶=偶 奇xor偶=奇 所以只要统计1的个数是奇数的数的个数 和 是偶数的个数 乘一起就行了 直接用bitset来做,虽然常数很小/数据随机可以过,但复杂度 ...
- Mysql插入、替换和无视
在现实的生产环境下,通常我们都会遇到这样的应用场景,需要我们更新数据.替换数据,若存在则不操作. insert into表示插入数据,数据库会检查主键,如果出现重复会报错: replace into表 ...
- UVALive - 6436(DFS)
题目链接:https://vjudge.net/contest/241341#problem/C 题目大意:给你从1到n总共n个数字,同时给你n-1个连接,同时保证任意两个点之间都可以连接.现在假设任 ...
- 部署kubernetes1.8.3高可用集群
Kubernetes作为容器应用的管理平台,通过对pod的运行状态进行监控,并且根据主机或容器失效的状态将新的pod调度到其他node上,实现了应用层的高可用. 针对kubernetes集群,高可用性 ...
- Python--Django学习笔记2
本篇介绍Django中的Model层. 首先介绍sqlite3,这是在当前版本中Django默认使用的数据库,sqlite也是Android中所使用的数据库. 接着介绍最最最常见的MySQL数据库如何 ...
- 洛谷P3195 玩具装箱TOY
题目大意: 有n个数,要将他们分成若干段,每一段的cost定义为: cost=r-l+ΣCk (k∈[r,l]) 该段的最终花费是:(cost-L)^2; 给出L,n,C(1~n),总共的最小花费. ...
- A1052. Linked List Sorting
A linked list consists of a series of structures, which are not necessarily adjacent in memory. We a ...
- 【洛谷P1486】郁闷的出纳员
题目大意:维护一个平衡树,支持插入一个数,删除小于一个值的所有数,K 大值查询,每个节点权值加减一个数. 题解:所有节点权值加减操作可以考虑直接维护一个全局标记,删除小于一个值的所有数字为一个二分的过 ...
- property(四十)
一个静态属性property本质就是实现了get,set,delete三种方法 用法: class Foo: @property def AAA(self): print('get的时候运行我啊') ...