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

Global และ Local Variables ใน Python: Scope และการใช้งาน

Python มี 2 ระดับ Variable Scope: Global (ทั่วโปรแกรม) และ Local (ภายในฟังก์ชัน)

Local Variables

เข้าถึงได้เฉพาะในฟังก์ชันที่ประกาศ

def func():
    x = "Python"  # Local
    print(x)

func()
print(x)  # NameError: name 'x' is not defined

Global Variables

เข้าถึงได้ทุกที่ในโมดูล รวมถึงในฟังก์ชัน

s = "Tutorialspoint"  # Global

def func():
    x = "Python"  # Local
    print(x)      # Python
    print(s)      # Tutorialspoint (เข้าถึง global ได้)

func()
print(s)  # Tutorialspoint

แก้ไข Global Variable ในฟังก์ชัน

ต้องใช้คำสั่ง global

z = 25

def func():
    global z
    print(z)  # 25
    z = 20    # เปลี่ยน global variable

func()
print(z)  # 20 (เปลี่ยนไปแล้ว)

ตัวอย่างผสม: Parameter, Local, Global

def func(x, y):
    global a
    a = 45          # กำหนด global a
    x, y = y, x     # swap local parameters
    b = 33          # local b
    b = 17          # เปลี่ยน local b
    c = 100         # local c
    print(a, b, x, y)  # 45 17 81 9

a, b, x, y = 3, 15, 3, 4
func(9, 81)
print(a, b, x, y)  # 45 15 3 4 (global a เปลี่ยน, อื่นๆ ไม่เปลี่ยน)

LEGB Rule (Scope Resolution Order)

  1. Local - ภายในฟังก์ชันปัจจุบัน
  2. Enclosing - ฟังก์ชันภายนอก (nested functions)
  3. Global - ระดับโมดูล
  4. Built-in - Python builtins (print, len, etc.)

Best Practices

  • หลีกเลี่ยง global variables มากเกินไป (ยากต่อการ debug/test)
  • ใช้ parameters และ return values แทน
  • ถ้าจำเป็น ต้องใช้ global keyword อย่างชัดเจน
  • Constants (UPPER_CASE) ระดับโมดูลถือว่า OK