简体   繁体   English

全局变量变为局部--UnboundLocalError:分配前引用了局部变量

[英]global var becomes local --UnboundLocalError: local variable referenced before assignment

I initialized rate as a global var: 我将rate初始化为全局变量:

import os, sys
rate=30

def foo():
    print('#########rate:', rate)
    if False:
        rate=int(sys.argv[2])


foo()

but when running the script, I get the following error: 但是在运行脚本时,出现以下错误:

Traceback (most recent call last):
  Line 10, in <module>
    foo()
  Line 5, in foo
    print('#########rate:', rate)
UnboundLocalError: local variable 'rate' referenced before assignment

although the if False: rate=int(sys.argv[2]) statement is not executed, it seems has some influence, is there some python rules explains this? 尽管未执行if False: rate=int(sys.argv[2])语句,但似乎有一定影响,是否有一些python规则对此进行了说明?

You should declare rate as global: 您应将rate声明为global:

import os, sys
rate=30

def foo():
    global rate # <----
    print('#########rate:', rate)
    if False:
        rate=int(sys.argv[2])


foo()

If there is assignment to a varaint (without global declaration), it is treated as local variable. 如果分配给变量(没有全局声明),则将其视为局部变量。

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

相关问题 UnboundLocalError:分配前已引用局部变量“(Var)” - UnboundLocalError: local variable '(Var)' referenced before assignment UnboundLocalError:<var>赋值前引用</var>的局部变量 - UnboundLocalError: local variable <var> referenced before assignment UnboundLocalError:在全局赋值之前引用的局部变量 - UnboundLocalError: local variable referenced before assignment whit global UnboundLocalError:分配前已引用局部变量“ truebomb” - UnboundLocalError: local variable 'truebomb' referenced before assignment UnboundLocalError:分配前已引用局部变量“ cur” - UnboundLocalError: local variable 'cur' referenced before assignment UnboundLocalError:分配前已引用局部变量“ Counter” - UnboundLocalError: local variable 'Counter' referenced before assignment UnBoundLocalError:赋值之前引用的局部变量(Python) - UnBoundLocalError: local variable referenced before assignment (Python) UnboundLocalError:分配前已引用局部变量“ strdate” - UnboundLocalError: local variable 'strdate' referenced before assignment UnboundLocalError:赋值之前引用了局部变量“ key” - UnboundLocalError: local variable 'key' referenced before assignment unboundLocalError:赋值前引用了局部变量“loopback” - unboundLocalError: local variable 'loopback' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM