当变量在python的if条件内创建时,我需要从if条件外部访问变量。if条件中的变量类型是test
是<type, str>
,而{
我试过下面的方法,但没用。在
在下面的代码中,我需要访问vn
和test
变量
for DO in range(count) :
atnnames = doc.getElementsByTagName("atnId")[DO]
atn = atnnames.childNodes[0].nodeValue
if atn == line[0]:
vn = doc.getElementsByTagName("vn")[DO]
vncontent = vn.childNodes[0].nodeValue
y = vncontent.encode('utf-8')
# print y
if '-' in y:
slt = (int(y.split('-')[0][-1]) + 1)
test = y.replace(y.split('-')[0][-1], str(slt))
# print test
else:
slt = (int(y.split('.')[-1]) + 1)
test = y.replace(y.split('.')[-1], str(slt))
# print test
else:
#print test
vn.firstChild.nodeValue = test
print vn.firstChild.nodeValue
当我运行上面的代码时得到的错误是
UnboundLocalError: local variable 'test' referenced before assignment
我尝试在for循环之前将变量定义为None
。在
这是在错误之下。
AttributeError: 'NoneType' object has no attribute 'firstChild'
用
None
在if
块之前定义变量,然后在if块中更新它。考虑以下因素:您的问题似乎是您引用的变量超出了它的范围。本质上,所发生的事情是在if语句中,您正在创建一个专用于if范围内使用的变量。实际上,当你说
print vn.firstChild.nodeValue
时,你也可以把它想象成任何其他变量,比如print undefinedVar
。所发生的是你在变量被定义之前引用(调用)。在不过,这里不用担心,因为这很容易修复。我们所能做的就是简单地创建您的vn并在if范围之外测试变量,因此在实际方法内部执行以下操作:
这基本上只是在最外面的范围内创建一个空变量。我将这些值设置为
None
,因为它们是在for循环运行后定义的。所以现在的情况是,有一个变量已经在外部声明,并且在开始时是None
,但是当您运行for循环时,您并不是在if语句内部创建一个临时变量,而是实际上更改了相关问题 更多 >
编程相关推荐