Python中的locals()函数和globals()函数

name = 'Tom'
age = 18


def func(x, y):
    sum = x + y
    _G = globals()
    _L = locals()
    print(id(_G), type(_G), _G)
    print(id(_L), type(_L), _L)


func(10, 20)

# 输出结果:
# 140622020688624 <class 'dict'> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fe51d92dc90>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/sunjiakuo/PycharmProjects/mytest/test4.py', '__cached__': None, 'name': 'Tom', 'age': 18, 'func': <function func at 0x7fe51d8aa050>}
# 140622020418608 <class 'dict'> {'x': 10, 'y': 20, 'sum': 30, '_G': {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fe51d92dc90>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/sunjiakuo/PycharmProjects/mytest/test4.py', '__cached__': None, 'name': 'Tom', 'age': 18, 'func': <function func at 0x7fe51d8aa050>}}
name = 'Tom'
age = 18

G = globals()
L = locals()
print(id(G), type(G), G)
print(id(L), type(L), L)

# 输出结果:
# 139768002771696 <class 'dict'> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f1e46239c90>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/sunjiakuo/PycharmProjects/mytest/test4.py', '__cached__': None, 'name': 'Tom', 'age': 18, 'G': {...}, 'L': {...}}
# 139768002771696 <class 'dict'> {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f1e46239c90>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/sunjiakuo/PycharmProjects/mytest/test4.py', '__cached__': None, 'name': 'Tom', 'age': 18, 'G': {...}, 'L': {...}}
  1. globals()函数以字典的形式返回定义该函数的模块内的全局作用域下的所有标识符(变量、常量等)
  2. locals()函数以字典的形式返回当前函数内的局域作用域下的所有标识符
  3. 如果直接在模块中调用globals()和locals()函数,它们的返回值是相同的

猜你喜欢

转载自blog.csdn.net/qq_36201400/article/details/108142044