1. 程式人生 > >python學習手冊(第4版) 第十七章 作用域

python學習手冊(第4版) 第十七章 作用域

變數的作用域由變數所在的檔案的位置決定的,而不是由函式呼叫決定的。

模組定義的是全域性作用域,此處的全域性,僅限於此模組;(整個專案的全域性變數,需要藉助於單例)

函式定義的是本地作用域,僅限於函式本身。

LEGB原則:

python搜尋4個作用域:本地作用域(Local function) -> 上一層def或lambda的本地作用域(Enclosing function locals) -> 全域性作用域(Global module) -> 內建作用域(Built-in python),

搜尋到變數後即停止,如果直至搜尋到內建作用域依然沒有時,將報錯。

內建作用域,簡單使用方法如下:

>>> 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 >>>