简体   繁体   English

如何判断变量是全局变量还是局部变量?

[英]How can I tell whether a variable is global or local?

如何判断Python中的变量是全局变量还是局部变量?

globals() will return a dict of global variables globals()将返回一个全局变量的字典

locals() will return a dict of local variables locals()将返回局部变量的字典

to check if the scope of the variable: 检查变量的范围:

if 'variable' in locals(): print("It's local") #Replace 'variable' with the variable
elif 'variable' in globals(): print("It's global") #But keep the quotation marks
else: print("It's not defined")

If you don't know about scopes, heres a good page to go to https://stackoverflow.com/a/292502/7486769 如果您不了解范围,请访问以下网址:https://stackoverflow.com/a/292502/7486769

If all you are doing is making a list for some documentation, all you need to do is create a list of variables that are defined outside of any function or class. 如果您要做的只是列出一些文档,那么您要做的就是创建一个在任何函数或类之外定义的变量的列表。

var1 = "something"

def foo():
    var2 = "something"

In the above, var1 is global, var2 is local. 在上面, var1是全局的, var2是局部的。

暂无
暂无

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

相关问题 如何检查是否存在全局或局部变量 - How can i check if there is a global or local variable 如何判断屏幕是否正在运行? - How can I tell whether screen is running? Python 如何识别函数中的变量是全局变量还是局部变量? - How does Python recognize whether a variable in a function is global or local? 如何在函数中使用 LOCAL VARIABLE,就像其他函数的 GLOBAL VARIABLE 变量 - How can I use LOCAL VARIABLE in function, like a GLOBAL VARIABLE variable for other function 如何判断发电机是否刚启动? - How can I tell whether a generator was just-started? 如何在没有全局变量的情况下解决“ UnboundLocalError:赋值之前引用了本地变量'foo'”错误? - How can I get around “UnboundLocalError: local variable 'foo' referenced before assignment” errors without global variables? 如何使 dataframe 全球化? 出现错误 - UnboundLocalError:分配前引用的局部变量 - How can I make a dataframe global? Getting error - UnboundLocalError: local variable referenced before assignment Anaconda:如何判断我是否选中了“将 Anaconda3 添加到我的 PATH 环境变量”框? - Anaconda: How do I tell whether I checked the box for "Add Anaconda3 to my PATH environment variable"? 我如何将此局部变量更改/设置为全局变量 - How do I change/set this Local variable into a global one 如何在Kivy中访问全局变量 - How can i access a global variable in kivy
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM