我需要在Python中,如果条件中创建的变量时,从如果条件访问外部变量。变量类型其是内部如果条件是test
是<type, str>
和vn
是<type, instance>
。
我曾尝试以下方法,但它并没有为我工作。
在下面的代码中,我需要访问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
我试图通过之前定义变量None
for循环。
它是抛出下面的错误。 AttributeError: 'NoneType' object has no attribute 'firstChild'
您的问题似乎是你引用其范围的变量之外的事实。本质上正在发生的事情是在你的if语句要创建一个变量专门使用的,如果范围内。有效,当你说你print vn.firstChild.nodeValue
也可以把它想象成是任何其他变量,如print undefinedVar
。什么是发生是您正在引用(呼叫)在变量,甚至被定义之前。
然而,在这里不用担心,因为这是很容易解决。我们所能做的仅仅是通过执行以下命令来创建你的VN和测试变量,如果范围之外,因此您的实际方法内:
vn = None
test = None
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
这基本上只是会在最外层范围的空变量。我已经设置的值,以None
因为他们得到一次你的循环运行定义。那么现在情况是你已经对外宣称一个变量,是None
在开始,但是当你运行你的for循环没有创建一个临时变量只是if语句里面,但你实际上是不断变化的价值
与if
的None
块之前定义变量,则在IF块进行更新。考虑以下:
y = None
x = 1
print(y)
if x == 1:
y = "d"
else:
y = 12
print(y)