合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
[Python Scopes and Namespaces](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces) [Scopes and Namespaces Example](https://docs.python.org/3/tutorial/classes.html#scopes-and-namespaces-example) 命名空间 --------- > A namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries 命名空间:名字到对象的映射。 Python通过命名空间记录变量,类似于字典中的 键->值 方式。 示例 ----- python程序执行期间会有2个或3个活动的命名空间(函数调用时有3个,函数调用结束后2个) 命令空间示例: - 内置命名空间 -- `builtins`模块 - 全局命名空间 -- 各个模块 - 本地命名空间 -- 函数 - 对象的属性集 -- 这其实也是命名空间 生命周期 ------------------ 各种命名空间在不同的时刻被创建,并且具有不同的生命周期。 - 内置命名空间 -- Python解释器启动时创建,且不被删除 - 全局命名空间 -- 读取模块时创建,通常持续至解释器退出 - 本地命名空间 -- 函数调用时创建,函数返回/引发异常时删除 locals() globals() -------------------- > locals() > Return a dictionary containing the current scope's local variables. > globals() > Return the dictionary containing the current scope's global variables. - locals() -- 返回一个字典,包含当前作用域的所有**本地**变量 - globals() -- 返回一个字典,包含当前作用域的**全局**变量 ~~~ print(locals()) print(globals()) def foo(x): s = 'abc' print(locals()) print(globals()) foo(1) # 运行结果如下: {'__name__': '__main__', '__doc__': None, 省略部分..., '__cached__': None} {'__name__': '__main__', '__doc__': None, 省略部分..., '__cached__': None} {'s': 'abc', 'x': 1} {'__name__': '__main__', '__doc__': None, 省略部分..., '__cached__': None, 'foo': <function foo at 0x00000000021C1EA0>} # notes: # 1) 第一行结果:locals()返回的是全局变量。因为语句在全局作用域内,全局作用域的本地变量即为全局变量。 # 2) 第四行结果:同是globals(),结果多出了`'foo':... ...`。 ~~~ locals()和globals()区别:**locals只读,globals可写。** locals()返回的是局部命名空间变量集的拷贝。改变其值,并不会添加/删除局部变量。 ~~~ def func(a = 1): b = 2 locs = locals() print(locs) # {'b': 2, 'a': 1} locs['c'] = 3 print(locs) # {'b': 2, 'a': 1, 'c': 3} print(c) # 报错!-- 并没有增加局部变量c func() ~~~ globals()的返回值改变,会添加/删除全局变量。 ~~~ a = 1 b = 2 glos = globals() print(glos) # {'__name__': '__main__', '__doc__': None, ... glos['c'] = 3 print(glos) # # {'__name__': '__main__', '__doc__': None, ... print(c) # 3 ~~~ import ... / from ... import ... ------------------------------------ `import xxx`:模块xxx本身被引入,保留了模块自身的命名空间,故使用`xxx.attr`格式访问其函数、变量。 from xxx import yyy:将yyy引入到了当前命名空间,故可直接使用。