如何判断变量是全局变量还是本地变量?

时间:2017-01-29 20:54:13

标签: python variables global local

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

2 个答案:

答案 0 :(得分:3)

globals()将返回全局变量的字典

locals()将返回局部变量的字典

检查变量的范围:

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")

如果你不了解范围,那么这是一个很好的页面,可以转到https://stackoverflow.com/a/292502/7486769

答案 1 :(得分:0)

如果你要做的就是为某些文档制作一个列表,那么你需要做的就是创建一个在任何函数或类之外定义的变量列表。

var1 = "something"

def foo():
    var2 = "something"

在上文中,var1是全局的,var2是本地的。