首页 > 解决方案 > 当变量在python的if-condition中定义时,如何在if-condition之后访问变量

问题描述

当在 python 的 if 条件中创建变量时,我需要从 if 条件之外访问变量。if-condition 中的变量类型是testis<type, str>vnis <type, instance>

我尝试了以下方法,但它对我不起作用。

在下面的代码中,我需要访问vntest变量

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

我尝试像以前一样定义变量Nonefor 循环。

它抛出错误。 AttributeError: 'NoneType' object has no attribute 'firstChild'

标签: pythonif-statementscope

解决方案


if用 定义块之前的变量None,然后在 if 块中更新它。考虑以下:

y = None
x = 1
print(y)
if x == 1:
    y = "d"
else:
    y = 12
print(y)

推荐阅读