在Python中,如何检查变量是否存在?
如果“x”存在,则打印“x存在”。
我问这个是因为我总是收到此错误:
UnboundLocalError at /settings/
local variable 'avatarlink' referenced before assignment
If "x" exists, then print "x exists".
I ask this because I always get this error:
UnboundLocalError at /settings/
local variable 'avatarlink' referenced before assignment
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么你需要知道?如果代码因此而中断,则可能是因为代码无论如何都是错误的并且需要修复。
也就是说,请尝试检查
if 'x' in locals()
或if 'x' in globals()
,根据您的预期情况进行检查。Why do you need to know? If the code breaks because of this, it's probably because the code is wrong anyway and needs to be fixed.
That said, try checking
if 'x' in locals()
orif 'x' in globals()
, as appropriate to where you're expecting it to be.正如 Python 中所说,“请求宽恕比请求许可更好”。因此,只需尝试访问该变量,如果它不存在,则捕获错误。
但是,我真的很想知道为什么您认为需要这样做。通常,您总是会在检查变量的值之前设置该变量。
As they say in Python, "it's better to ask forgiveness than permission". So, just try and access the variable, and catch the error if it doesn't exist.
However, I would really like to know why you think you need to do this. Usually, you would always set the variable before checking its value.
您可以检查 x 是否在
globals()
或locals()
中。You may check if x is in
globals()
orlocals()
.在 python 中,你确实不应该使用尚未设置的变量。如果需要,您可以将 avatarLink 设置为 None。
In python you really shouldn't be using variables which haven't been set. If need be you can set avatarLink to None.