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. Can you answer these queries? HDU - 4027(线段树+技巧)

    题意:给一个数组序列, 数组长度为100000 两种操作: 一种操作是将某一个固定区间所有数开方(向下取整) 另一种操作是询问某个区间的所有数字之和. 由于数不超过263,因此开个七八次就变成1,由于 ...

  2. Leetcode 326.3的幂 By Python

    给定一个整数,写一个函数来判断它是否是 3 的幂次方. 示例 1: 输入: 27 输出: true 示例 2: 输入: 0 输出: false 示例 3: 输入: 9 输出: true 示例 4: 输 ...

  3. Python的栈和队列实现

    栈 class Node: def __init__(self, data=None): self.next = None self.data = data class Stack: def __in ...

  4. hdu 2158 最短区间版大家来找碴(尺取法)

    Problem Description 给定一个序列,有N个整数,数值范围为[0,N).有M个询问,每次询问给定Q个整数,可能出现重复值.要求找出一个最短区间,该区间要包含这Q个整数数值.你能找的出来 ...

  5. eclipse index 不工作 F3 不能找到头文件

    To add paths containing code to parse, follow these steps :1. Right click on the project2. Select Pr ...

  6. 2019.3.18考试&2019.3.19考试&2019.3.21考试

    2019.3.18 C O D E T1 树上直接贪心,环上for一遍贪心 哇说的简单,码了将近一下午终于码出来了 感觉自己码力/写题策略太糟糕了,先是搞了一个细节太多的写法最后不得不弃疗了,然后第二 ...

  7. AtCoder Grand Contest 004 C - AND Grid

    题意: 给出一张有紫色点的网格,构造一张红点网格和一张蓝点网格,使红蓝点的交集为紫色点. 保证网格四周没有紫色点. 构造一下,使蓝点和红点能够到每个点. #include<bits/stdc++ ...

  8. [HEOI2013]SAO ——计数问题

    题目大意: Welcome to SAO ( Strange and Abnormal Online).这是一个 VR MMORPG, 含有 n 个关卡.但是,挑战不同关卡的顺序是一个很大的问题. 有 ...

  9. 【LOJ#6282】数列分块6

    题目大意:给定一个由 N 个数组成的序列,维护两种操作:单点询问,单点插入.N < 100000 题解:在块内维护一个链表,支持动态插入数字,同时对于非随即数据来说,若块的大小过大,需要重构. ...

  10. 【POJ1961】最短周期串/最大周期 kmp

    引理:\(s[1,i]\) 具有长度为 \(len\) 的循环节的充要条件是:\(len\ |\ i,s[1,i-len]=s[len+1,i]\). 代码如下 #include <cstdio ...