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的更多相关文章

  1. _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 ...

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

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

  3. 变量引用的错误:UnboundLocalError: local variable 'range' referenced before assignment

    class Battery(): """一次模拟电瓶汽车的简单尝试""" def __init__(self,battery_size = ...

  4. UnboundLocalError: local variable 'range' referenced before assignment

    1. 报错信息 UnboundLocalError: local variable 'range' referenced before assignment 2. 代码 class Car(): &q ...

  5. 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 ...

  6. 出现UnboundLocalError: local variable 'a' referenced before assignment异常的情况与解决方法

    出现UnboundLocalError: local variable ‘a’ referenced before assignment异常的情况与解决方法字面意思:局部变量赋值前被引用原因:局部变量 ...

  7. This inspection warns about local variables referenced before assignment.

    关于 local variable 'has' referenced before assignment 问题 今天在django开发时,访问页面总是出现错误提示“local variable 'ha ...

  8. jsp的<%@ include file="jsp/common.jsp" %>报错误Duplicate local variable basePath

    将公共引入的文件放到common.jsp中,其他页面引入该jsp即可使用 <%@ page language="java" import="java.util.*& ...

  9. UnboundLocalError: local variable 'foo' referenced before assignment Python常见错误

    在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在) 在函数中使用局部变来那个而同时又存在同名全局变量时是很复杂的, 使用规则:如果在函数中定义了任何东西,如果它只是在函数中使用 ...

随机推荐

  1. Django-website 程序案例系列-18 多表跨表操作优化

    详解Django的 select_related 和 prefetch_related 函数对 QuerySet 查询的优化 在数据库有外键的时候,使用 select_related() 和 pref ...

  2. BZOJ5306 HAOI2018染色(容斥原理+NTT)

    容易想到枚举恰好出现S次的颜色有几种.如果固定至少有i种恰好出现S次,那么方案数是C(M,i)·C(N,i*S)·(M-i)N-i*S·(i*S)!/(S!)i,设为f(i). 于是考虑容斥,可得恰好 ...

  3. SQL将Null转化为0

    使用ifnull() ) ; 使用判断 public function getGold($table,$querry,$start,$end,$status,$field) { $gold = Db: ...

  4. MT【231】棋子方法数

    设有5枚无区别的棋子放在如图$5*5$的棋盘的小方格中,放棋子的规则是每行每列放且仅放一个棋子,同时,不允许放在黑方格内,则共有______ 方法. 答案:5的错排数44.第一行的数不放第二列(相当于 ...

  5. SharePoint 错误集 2

    1 Run command “New-SPConfigurationDatabase" Feature Description: error message popup after run ...

  6. React Native——组件的生命周期

    组件生命周期 上流程图描述了组件从创建.运行到销毁的整个过程,可以看到如果一个组件在被创建,从开始一直到运行会依次调用getDefaultProps到render这五个函数:在运行过程中,如果有属性和 ...

  7. WC 2019 记

    “在下一次挑战来临时,还能否有足够的勇气和力量重新提起这被震掉两次的剑呢?” 难得来参加一次$WC$,这是第一次来,也很有可能是最后一次了(我也好希望有下一次啊,哪怕这可能再渺小,如同浩瀚星空中一丝辰 ...

  8. Android log 方法

    package test; public abstract class Logger { private static Class<? extends Logger> mLoggerCla ...

  9. 【POJ3635】Full Tank 优先队列BFS

    普通BFS:每个状态只访问一次,第一次入队时即为该状态对应的最优解. 优先队列BFS:每个状态可能被更新多次,入队多次,但是只会扩展一次,每次出队时即为改状态对应的最优解. 且对于优先队列BFS来说, ...

  10. 那些神奇的before和after使用方法

    在英文单词里面:before是在什么之前.after是在什么之后.诚然,在我们的css里面, 通过使用before和after伪类元素,可以在我们想要的元素前面或者后面插入内容. 下面是使用befor ...