探討 :: 命名空間與可視範圍
Name (also called identifier) is simply a name given to objects. Everything in Python is an object. Name is a way to access the underlying object.
To simply put it, namespace is a collection of names.
Different namespaces can co-exist at a given time but are completely isolated.
- Built-in Namespace
- Module: Global Namespace
- Function: Local Namespace
Although there are various unique namespaces defined, we may not be able to access all of them from every part of the program. The concept of scope comes into play. Scope is the portion of the program from where a namespace can be accessed directly without any prefix. At any given moment, there are at least three nested scopes.
- Scope of the current function which has local names
- Scope of the module which has global names
- Outermost scope which has built-in names
We have seen that multiple namespaces can exist independently from each other and that they can contain the same variable names on different hierachy levels. The “scope” defines on which hierarchy level Python searches for a particular “variable name” for its associated object. Now, the next question is: “In which order does Python search the different levels of namespaces before it finds the name-to-object’ mapping?” To answer is: It uses the LEGB-rule, which stands for Local -> Enclosed -> Global -> Built-in, where the arrows should denote the direction of the namespace-hierarchy search order.
- Local can be inside a function or class method, for example.
- Enclosed can be its enclosing function, e.g., if a function is wrapped inside another function.
- Global refers to the uppermost level of the executing script itself, and
- Built-in are special names that Python reserves for itself.
參考資料
- http://www.programiz.com/python-programming/namespace
- http://spartanideas.msu.edu/2014/05/12/a-beginners-guide-to-pythons-namespaces-scope-resolution-and-the-legb-rule/
補充資料
- 套件層級 , 定義在
__init__.py
- 模組層級 , 定義在
module_file.py
- 類別層級 , 定義在
class_suite
- 實例層級 , 定義在
__init__(self)
, 使用self.
定義