Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Namespace และ Variable Scope (LEGB Rule)

Namespace = Mapping ชื่อ → Object | Scope = พื้นที่ที่ชื่อมองเห็นได้

LEGB Rule (ลำดับการค้นหา)

  1. L - Local: ภายใน Function/Lambda (Assignment, Parameter)
  2. E - Enclosing: ฟังก์ชันภายนอก (Nested Functions) เรียกจากในออกไป
  3. G - Global (Module): Top-level Module, หรือ global Statement
  4. 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