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)
- Local - ภายในฟังก์ชันปัจจุบัน
- Enclosing - ฟังก์ชันภายนอก (nested functions)
- Global - ระดับโมดูล
- Built-in - Python builtins (print, len, etc.)
Best Practices
- หลีกเลี่ยง global variables มากเกินไป (ยากต่อการ debug/test)
- ใช้ parameters และ return values แทน
- ถ้าจำเป็น ต้องใช้
globalkeyword อย่างชัดเจน - Constants (UPPER_CASE) ระดับโมดูลถือว่า OK