简体   繁体   English

Python奇怪的变量范围问题

[英]Python weird variable scope issue

I have my code as below. 我的代码如下。

def test():
   print num1
   print num
   num += 10

if __name__ == '__main__':
   num = 0
   num1 = 3
   test()

When executing the above python code I get the following output. 执行上面的python代码时,我得到以下输出。

3 
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "<stdin>", line 2, in test
UnboundLocalError: local variable 'num' referenced before assignment

I do not know why particularly num is not available in test method. 我不知道为什么在测试方法中没有特别的数字。 It is very weird for me and i did not face this yet before. 这对我来说非常奇怪,我之前没有面对过这个问题。

Note: I am using python 2.7. 注意:我使用的是python 2.7。

Since you're assigning to num inside the test function, python considers it to be a local variable. 由于您在test函数中分配给num ,因此python将其视为局部变量。 This is why it complains that you are referencing to a local variable before assigning it. 这就是为什么它会在分配之前抱怨你引用一个局部变量。

You can fix this by explicitly declaring num to be global: 您可以通过明确声明num为全局来解决此问题:

def test():
    global num
    print num1
    print num
    num += 10

if __name__ == '__main__':
    num = 0
    num1 = 3
    test()

num appears in an assignment statement inside the definition of the test . num出现在test定义内的赋值语句中。 This makes num a local variable. 这使num成为局部变量。 Since scope determination is made at compile time, num is a local variable even in the print statement that precedes the assignment. 由于范围确定是在编译时进行的,因此即使在赋值之前的print语句中, num也是局部变量。 At that time, num has no value, resulting in the error. 那时, num没有值,导致错误。 You need to declare num as global if you want to access the global value. 如果要访问全局值,则需要将num声明为全局。 num1 does not have this problem, since you never try to assign to it. num1没有此问题,因为您从不尝试分配给它。

def test():
    global num
    print num1
    print num
    num += 10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM