命名空间&作用域
1. 命名空间
1.1 定义
- 什么是命名空间?
命名空间(namespace)是名称到对象的映射,当前大部分命名空间都是通过 Python 字典来实现的,它的主要作用是避免项目中的名字冲突,每一个命名空间都是相对独立的,在不同的命名空间中可以同名,在相同的命名空间中不可以同名
1.2 类型
- 本地(局部)命名空间
- 定义:包含函数内的本地名称。
- 生命周期:调用函数时会创建此命名空间,它只会持续到函数返回。函数调用结束后,也就会销毁。
def func():
name = 'nancy' # 此处的 name 就是存在于本地命名空间
print(f'hello {name}')
- 全局命名空间
- 定义:包含项目中使用的各种导入模块的名称。
- 生命周期:在模块包含在项目中时创建的,并且一直持续到脚本结束,Python解释器退出时销毁。当某个模块被入导后之,该模块同时引入了一个命名空间,其中含包模块中有所的名称和关联的对象,可以通过存储在每个模块中的__dict__来查看这个命名空间,换句话说,字典就是这个模块的命名空间。
import os
name = 'nancy' # 此时的 name 存在于全局空间
print(os.__dict__) # os 模块内置的所有方法和属性此时也存在于全局空间
- 内置命名空间
- 定义:包含内置函数和内置异常名称。
- 生命周期:在 Python 解释器启动时创建,退出时销毁。
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
# 打印出内置函数和属性
2. 作用域
2.1 定义
变量所起作用的范围,超出范围则某变量不能被使用。在python 程序中,直接访问一个变量,会从内到外依次访问所有的作用域直到找到,否则报错。
- 补充:Python 中只有模块(module),类(class)以及函数(def、lambda)才会产生新的作用域,其它的代码块(如 if | elif | else、try | except、for | while等)是不会产生新的作用域的。
2.2 种类
- Local:最内层,包含局部变量,一般指的是函数内部的作用域。
- Enclosing:包含非局部但是也不是全局的变量,主要是嵌套时,外层函数的变量,那么相对内层函数来说,嵌套的外层函数中的变量既不是局部变量也不是全局变量。
- Global:全局变量,例如当前模块中的全局变量。
- Build-in:内置变量。
2.3 顺序
- 搜索顺序
- 局部:最先被搜索的最内部作用域,包含局部名称。
- 嵌套:根据嵌套层次由内向外搜索,包含非全局、非局部名称。
- 全局:倒数第二个被搜索,包含当前模块的全局名称。
- 内建:最后被搜索,包含内置名称的命名空间。
- 查找顺序:LEGB – Loacl >> Enclosing >> Global >> Build-in
- 图示
- 实例
a = 1 # 全局作用域 global
def outer():
b = 2 # 嵌套作用域 enclosing
def inner():
c = 3 # 局部作用域 local
name = 'nancy'
def func():
name = 'roy'
print(name) # print()函数的调用在函数内(局部),所以name的查找范围是 local > enclosing > global > built-in
func()
print(name) # 此处的print()函数的调用在全局内(global),所以name的查找范围是 global > built-in
# roy
# nancy
2.4 作用域的改变
- 全局变量:定义在函数外部的变量。
- 局部变量:定义在函数内部的变量。
全局变量可以在整个程序范围内进行访问,而局部变量只能在函数内部访问
当我们想让内部作用域修改外部作用域的变量的时候,就要用到 global 和 nonlocal
2.4.1 global
name = 'nancy' # 全局变量
def func():
global name # 使用 global 声明 name 为全局变量
name = 'roy'
print(name)
func()
print(name)
# roy
# roy
2.4.2 nonlocal
- 使用 nonlocal 前
def outer():
name = 'roy'
def inner():
name = 'nancy'
print('inner:', name)
inner()
print('outer:', name)
outer()
# inner: nancy
# outer: roy
- 使用 nonlocal 后
def outer():
name = 'roy'
def inner():
nonlocal name # 使用 nonlocal 声明 name 为外层作用域
name = 'nancy'
print('inner:', name)
inner()
print('outer:', name)
outer()
# inner: nancy
# outer: nancy