Namespace = Mapping ชื่อ → Object | Scope = พื้นที่ที่ชื่อมองเห็นได้
LEGB Rule (ลำดับการค้นหา)
- L - Local: ภายใน Function/Lambda (Assignment, Parameter)
- E - Enclosing: ฟังก์ชันภายนอก (Nested Functions) เรียกจากในออกไป
- G - Global (Module): Top-level Module, หรือ
globalStatement - B - Built-in:
open,len,Exception,print(Python 3) ...
ตัวอย่างครบวงจร
x = 'global' # G
def outer():
x = 'enclosing' # E
def inner():
x = 'local' # L
print(x) # 'local'
inner()
print(x) # 'enclosing'
outer()
print(x) # 'global'
คำสั่งควบคุม
global x→ ผูก/แก้ไขที่ Module Scope (G)nonlocal x→ ผูก/แก้ไขที่ Enclosing Scope (E) (Python 3+)
Class Scope (Special)
- Class Body เป็น Scope แยก (ไม่ใช่ Enclosing ของ Method)
- Method ไม่เห็น Class Variable โดยตรง ต้องใช้
ClassName.attrหรือself.attr