global keyword ใช้ประกาศตัวแปรภายในฟังก์ชันว่าเป็น Global Variable (เข้าถึง/แก้ไขได้ทั่วโปรแกรม)
1. ตัวแปรนอกฟังก์ชัน (Global โดยอัตโนมัติ)
x = 56
def func():
y = x * 2 # อ่าน x ได้ (Global scope)
return y
print(func()) # 112
2. พยายามแก้ไข Global ในฟังก์ชัน (Error)
x = 56
def func():
y = x * 2
x = x + 2 # Error! Python คิดว่า x เป็น Local variable
return y
func() # UnboundLocalError: local variable 'x' referenced before assignment
3. ใช้ global keyword แก้ไข
x = 56
def func():
global x
x = x + 2 # แก้ไข Global x ได้
y = x * 2
return y
print(func()) # 116
print(x) # 58 (Global x เปลี่ยนไปแล้ว)
4. Global ใน Nested Function
def outer():
x = 56
def inner():
global x # อ้างอิง Module-level x, ไม่ใช่ outer's x
x = 20
print("x in inner:", x) # 20
x += 3
print("y in inner:", x * 2) # 46
inner()
print("x in outer:", x) # 56 (outer's x ไม่เปลี่ยน!)
outer()
print("x global:", x) # 20 (Module-level x เปลี่ยน!)
ผลลัพธ์
x in inner: 20 y in inner: 46 x in outer: 56 x global: 20
สรุป: global ใน Nested function อ้างถึง Module-level scope ไม่ใช่ Enclosing scope (ใช้ nonlocal สำหรับ Enclosing scope)