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