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

Variable Scope ใน Python Modules (กฎ LEGB)

Scope (ขอบเขต) ใน Python ควบคุมโดย Namespace ตัวแปรถูกค้นหาตามลำดับ LEGB Rule:

  1. L - Local: ตัวแปรที่กำหนดในฟังก์ชัน/แลมบ์ดา (ไม่ได้ประกาศ global)
  2. E - Enclosing: ตัวแปรในฟังก์ชันภายนอกที่ห่อหุ้ม (Nested Functions) เรียกจากในออกไป
  3. G - Global (Module): ตัวแปรระดับบนสุดของโมดูล หรือที่ประกาศ global ในฟังก์ชัน
  4. B - Built-in: ชื่อสำรองของ Python (open, range, Exception, ...)

ตัวอย่าง

x = 'global'  # G

def outer():
    x = 'enclosing'  # E
    def inner():
        x = 'local'  # L
        print(x)     # พิมพ์ 'local'
    inner()
    print(x)         # พิมพ์ 'enclosing'

outer()
print(x)             # พิมพ์ 'global'

คำสั่งควบคุม Scope

  • global x → ใช้/แก้ไขตัวแปรระดับ Module (G)
  • nonlocal x → ใช้/แก้ไขตัวแปรระดับ Enclosing (E) (Python 3+)