locals()
locals 函数更新并以字典形式返回当前全部局部变量
例子:
#1
a = 9
b = 4
print(locals())
#2
for i in range(2):
c = 8
print(locals())
#3
def checklocals(m):
b = 1
print(locals())
checklocals(999)
结果:
#1
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fbbc19a47b8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'try.py', '__cached__': None, 'a': 9, 'b': 4}
#2
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fbbc19a47b8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'try.py', '__cached__': None, 'a': 9, 'b': 4, 'i': 0, 'c': 8}
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fbbc19a47b8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'try.py', '__cached__': None, 'a': 9, 'b': 4, 'i': 1, 'c': 8}
#3
{'m': 999, 'b': 1}
思考:
- 如果locals()出现在函数模块主体中,则会返回模块的默认局部变量
- locals() 会返回直到函数本身位置的所有局部变量,local本行后面的变量不会被返回
- 如果locals()只出现在模块中的某个函数定义中, 当声明此函数时,返回此函数中的局部变量与函数输入参数