每个都返回一个字典:
> globals()总是返回模块命名空间的字典
> locals()总是返回当前命名空间的字典
> vars()返回当前命名空间的字典(如果没有参数调用)或参数的字典。
本地和vars可以使用一些更多的解释。如果在函数内调用locals(),它会构造函数名字空间的字典,并返回它 – 任何进一步的名称赋值不会反映在返回的字典中,并且字典的任何赋值都不会反映在实际本地命名空间:
def test():
a = 1
b = 2
huh = locals()
c = 3
print(huh)
huh['d'] = 4
print(d)
给我们:
{'a': 1, 'b': 2}
Traceback (most recent call last):
File "test.py", line 30, in
test()
File "test.py", line 26, in test
print(d)
NameError: global name 'd' is not defined
两个注释:
>这种行为是CPython特有的 – 其他Pythons可能允许更新使其回到本地命名空间
>在CPython 2.x中,可以通过在函数中放置一个exec“pass”行来使它工作。
如果在函数外调用locals(),它返回当前命名空间的实际字典。对命名空间的进一步更改将反映在字典中,对字典的更改将反映在命名空间中:
class Test(object):
a = 'one'
b = 'two'
huh = locals()
c = 'three'
huh['d'] = 'four'
print huh
给我们:
{
'a': 'one',
'b': 'two',
'c': 'three',
'd': 'four',
'huh': {...},
'__module__': '__main__',
}
到目前为止,我所说的关于locals()的所有内容对于vars()也是如此。vars()接受一个单独的对象作为它的参数,如果你给它一个对象,它返回__dict__目的。如果该对象不是函数,则返回的__dict__是该对象的命名空间:
class Test(object):
a = 'one'
b = 'two'
def frobber(self):
print self.c
t = Test()
huh = vars(t)
huh['c'] = 'three'
t.frobber()
这给了我们:
three
如果对象是一个函数,你仍然得到它的__dict__,但除非你做有趣和有趣的东西,它可能不是非常有用:
def test():
a = 1
b = 2
print test.c
huh = vars(test) # these two lines are the same as 'test.c = 3'
huh['c'] = 3
test()
这给了我们:
3