简体   繁体   English

全局变量仍然存在我得到“UnboundLocalError:赋值前引用的局部变量'a'”

[英]Global variable exists still I get "UnboundLocalError: local variable 'a' referenced before assignment"

The following python code gives an error.以下 python 代码给出了一个错误。 Why isn't it referencing the global variable a?为什么不引用全局变量a?

a = 10

def b(x):
    if(x == True):
        a = 2
    return a

print(b(False))

The error:错误:

Traceback (most recent call last):
  File "<string>", line 8, in <module>
File "<string>", line 6, in b
UnboundLocalError: local variable 'a' referenced before assignment
> 

The issue is that you're using a local variable that has the same name of the global one.问题是您使用的局部变量与全局变量同名。 This can help: Modifying global variable with same name as local variable这可以帮助: Modifying global variable with same name as local variable

Edit: in fact, this seems to be working:编辑:事实上,这似乎有效:

a = 10

def b(x):
    if(x == True):
        globals()['a'] = 2
    return a

print(b(False))

暂无
暂无

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

相关问题 UnboundLocalError:赋值前引用了局部变量“i” - UnboundLocalError: local variable 'i' referenced before assignment 赋值之前引用了unboundlocalerror局部变量&#39;i&#39; - unboundlocalerror local variable 'i' referenced before assignment 如何在没有全局变量的情况下解决“ UnboundLocalError:赋值之前引用了本地变量&#39;foo&#39;”错误? - How can I get around “UnboundLocalError: local variable 'foo' referenced before assignment” errors without global variables? 全局变量变为局部--UnboundLocalError:分配前引用了局部变量 - global var becomes local --UnboundLocalError: local variable 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
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM