python学习手册(第4版) 第十七章 作用域

变量的作用域由变量所在的文件的位置决定的,而不是由函数调用决定的。

 

模块定义的是全局作用域,此处的全局,仅限于此模块;(整个项目的全局变量,需要借助于单例)

函数定义的是本地作用域,仅限于函数本身。

 

LEGB原则:

python搜索4个作用域:本地作用域(Local function) -> 上一层def或lambda的本地作用域(Enclosing function locals) -> 全局作用域(Global module) -> 内置作用域(Built-in python),

搜索到变量后即停止,如果直至搜索到内置作用域依然没有时,将报错。

 

python学习手册(第4版) 第十七章 作用域

 

内置作用域,简单使用方法如下:

>>> import builtins
>>> 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']
>>> zip
<built-in function zip>

>>> __builtin__.zip
<built-in function zip>
>>>

 

global是对命名空间的声明,在本地作用域中声明变量为全局作用域

 

变量名的封装:每个模块都是自包含的命名空间,一个模块只有通过导入另一个模块才能看到它内部的变量。

一个模块被导入,其全局作用域实际上构成了一个对象的属性。

导入者自动获得被导入模块的所有全局变量的访问权

 

模块之间传递变量,最好是调用方法,传参和返回值,实现传递,避免模块多层继承后,直接修改其全局变量,会导致紊乱。

 

nonlocal是对命名空间的说明,在本地作用域中声明为上一个作用域(也可称为完全略过本地作用域),LEGB依次向上。

只有使用nonlocal,能对被导入模块的变量进行修改,否则只是在当前模块中赋值而已。

 

lambda的使用,相当于引入了新的本地作用域,使用嵌套作用域查找层,进行变量赋值,如下:

>>> def func():
...     x = 4
...     action = (lambda n:x**n)               # 此处相当于嵌套了一个def
...     return action
...
>>> f = func()
>>> print(f(2))
16
>>>

 

嵌套函数举例:

>>> def f1(a):
...     def f2(b):
...         return a**b
...     return f2                              # 这里需要返回嵌套函数,否则在外部无法调用嵌套函数
...
>>> f = f1(2)
>>> f(3)
8
>>>

 

了解一下作用域查找层,LEGB,当本地作用域没有此变量时,会向上一层去查找,如下例子可以求证,

>>> x = 'abc'
>>> def func():
...     print(x)
...
>>> func()
abc
>>>