locals() 如果在函数中调用则为局部变量字典,否则为全局变量字典>>> f
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
f
NameError: name 'f' is not defined
>>> locals()['f']=0
>>> f
0
>>> f=str()
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'f': ''}
>>> del f #等价于 del locals()['f']
>>> locals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
>>> a=0
>>> b=True
>>> c=()
>>> d='Hi'
>>> a
0
>>> b
True
>>> c
()
>>> d
'Hi'
>>> locals().clear()
>>> a
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
a
NameError: name 'a' is not defined
>>> b
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
b
NameError: name 'b' is not defined
>>> c
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
c
NameError: name 'c' is not defined
>>> d
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
d
NameError: name 'd' is not defined
|