程序运行起来后,内存中有各个层级的namespace,Python也不例外,有人喜欢把namespace成为符号表,在Python中,namespace其实就是一个python的Dict变量。
在Python中,我们可以很方便的用两个内置的函数,来查看
def test(arg):
z = 1
print(locals())
test(6)
test('maixj.net')
print(globals())
运行结果:
D:\pytest>python test.py
{'z': 1, 'arg': 6}
{'z': 1, 'arg': 'maixj.net'}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_f
rozen_importlib_external.SourceFileLoader object at 0x00712330>, '__spec__': Non
e, '__annotations__': {}, '__builtins__': , '__fil
e__': 'test.py', '__cached__': None, 'test': }
这个全局符号表内容还不多,再看看这个,我自己用来做python随手测试的窗口内容:
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {
}, '__builtins__': , 'a': {...}, 'b': 'aa\nbb', 'c
': 'abc', '人': 123, 'list1': ['1', 1, 5, 1, 2, 3], 'list2': ['1', 1, 5, 1, 2, 3
], 'list3': [6, 2, 3, 4], 'list4': [5, 2, 3, 6, 2, 3, 4], 'list6': [1, [9, 3]],
'list7': [4, [9, 6]], 'list8': [1, [9, 3], 4, [9, 6]], 'x': range(0, 5), 'jj': [
'a', 'b', 'c'], 'ss': '.', 'args': (3, 6)}
>>>
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__pack
age__', '__spec__', 'a', 'args', 'b', 'c', 'jj', 'list1', 'list2', 'list3', 'lis
t4', 'list6', 'list7', 'list8', 'ss', 'x', '人']
>>>
>>> len(globals())
22
>>> len(dir())
22
>>>
dir()只是把符号名称全部列出来,globals()还要将符号对应的值列出。注意一个细节:以上代码中包含一个变量为“人”的变量,这是可以的,但是不符合一般的Python编程规范,我这里只是测试。