当变量在python的if-condition中定义时,如何在if-condition之后访问变量 [英] How to access the variables after if-condition when the variable is defined inside the if-condition in python

查看:407
本文介绍了当变量在python的if-condition中定义时,如何在if-condition之后访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在python的if-condition内部创建变量时,我需要从if-condition外部访问变量。 if条件中的变量类型为 test < type,str> vn <类型,实例>



我尝试了以下方法



在下面的代码中,我需要访问 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')
#如果是'-',则打印y
y:
slt =(int(y.split('-')[0] [-1])+1)
test = y.replace(y.split('-')[0 ] [-1],str(slt))
#打印测试
否则:
slt =(int(y.split('。')[-1])+ 1)
test = y.replace(y.split('。')[-1],str(slt ))
#打印测试
其他:
#print测试
vn.firstChild.nodeValue =测试
打印vn.firstChild.nodeValue

运行上面的代码时遇到的错误是



UnboundLocalError:赋值之前引用了局部变量'test'



我尝试将变量定义为没有。



并且它抛出以下错误。
AttributeError:'NoneType'对象没有属性'firstChild'

解决方案

您的问题似乎是您在引用变量范围之外的事实。本质上发生的事情是在if语句中,您正在创建一个专用于if范围内的变量。实际上,当您说出 print vn.firstChild.nodeValue 时,您也可以将其想象为任何其他变量,例如 print undefinedVar 。发生的事情是您在变量尚未定义之前就已对其进行引用(调用)。



但是,这里无后顾之忧,因为这很容易解决。我们可以做的就是简单地在if范围之外创建您的vn和测试变量,因此可以通过以下操作在您的实际方法中创建:

  vn =无
测试=无

表示范围(计数)中的溶解氧:
atnnames = doc.getElementsByTagName( atnId)[ DO]
atn = atnnames.childNodes [0] .nodeValue
如果atn ==第[0]行:
vn = doc.getElementsByTagName( vn)[DO]
vncontent = vn.childNodes [0] .nodeValue
y = vncontent.encode('utf-8')
#打印y
如果y中的'-':
slt =( int(y.split('-')[0] [-1])+ 1)
test = y.replace(y.split('-')[0] [-1],str(slt ))
#打印测试
否则:
slt =(int(y.split('。')[-1])+ 1)
test = y.replace( y.split('。')[-1],str(slt))
#打印测试
否则:
#打印测试
vn.firstChild.nodeValue = test
打印vn.firstChild.nodeValue

这基本上只是在最外层范围内创建一个空变量。我将这些值设置为,因为一旦您的for循环运行,它们就会被定义。所以现在发生的是,您有一个在外部声明的变量,开始时是 None ,但是在运行for循环时,您并不会创建临时变量在if语句中,但实际上是在更改$
的值

I need to access variable from outside of if-condition when the variable is created inside the if-condition in python. The variable types which are inside if-condition are test is <type, str> and vn is <type, instance>.

I have tried the below way but it has not worked for me.

In the below code I need to access vn and test variables

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

The error I'm getting when I run the above code is

UnboundLocalError: local variable 'test' referenced before assignment

I tried by defining the variables as None before for loop.

and It is throwing below error. AttributeError: 'NoneType' object has no attribute 'firstChild'

解决方案

Your problem appears to be the fact that you are referencing a variable outside of its scope. Essentially what is happening is in your if statement you are creating a variable exclusively for use within the if scope. Effectively when you have said print vn.firstChild.nodeValue you can also imagine it as being any other variable such as print undefinedVar. What is occuring is your are referencing (calling) upon the variable before it has even been defined.

However, no worries here since this is very easy to fix. What we can do is simply create your vn and test variables outside of the if scope, hence inside your actual method by doing the following:

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

This basically just creates an empty variable in the outermost scope. I've set the values to None since they get defined once your for loop runs. So what happens now is you have a variable which has been declared outside, and is None at the start, but as you run your for loop you are not creating a temporary variable just inside the if statement, but you are actually changing the value of

这篇关于当变量在python的if-condition中定义时,如何在if-condition之后访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆