python程序执行期间会有3个活动的命名空间,按照变量定义的位置,可以划分为以下3类:
Local,局部命名空间,每个函数所拥有的命名空间,记录了函数中定义的所有变量,包括函数的入参、内部定义的局部变量。
Global,全局命名空间,每个模块加载执行时创建的,记录了模块中定义的变量,包括模块中定义的函数、类、其他导入的模块、模块级的变量与常量。
Built-in,python自带的内建命名空间,任何模块均可以访问,放着内置的函数和异常。
程序执行过程访问名称空间顺序是Local-->Global-->Built-in.
eg:
print(id(locals()))print(id(globals()))print(‘Built-in:‘ + str(locals()))g=7class Test(object): y=2 def __init__(self,x): print(‘--------‘) print(g) print(‘Local:‘ + str(locals())) print(‘---->‘) print(‘Global:‘ + str(globals())) print(‘-------‘) pass
out:
140458094155656
140458094155656
Built-in:{‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__doc__‘: None, ‘__spec__‘: None, ‘__package__‘: None, ‘__name__‘: ‘__main__‘, ‘__cached__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x7fbef2ca3eb8>, ‘__file__‘: ‘/home/z/PycharmProjects/scripts/yong.py‘}
--------
7
Local:{‘self‘: <__main__.Test object at 0x7fbef0ff8400>, ‘x‘: <function hello at 0x7fbef2cf0048>}
---->
Global:{‘Test‘: <class ‘__main__.Test‘>, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘__doc__‘: None, ‘g‘: 7, ‘__spec__‘: None, ‘__package__‘: None, ‘__name__‘: ‘__main__‘, ‘__cached__‘: None, ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x7fbef2ca3eb8>, ‘__file__‘: ‘/home/z/scripts/yong.py‘}
-------
原文地址:https://www.cnblogs.com/linux-1921/p/12520425.html