[英]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.