Global Variable ใน Python คืออะไร?
Global Variable คือ Variable ที่ประกาศนอก Function แต่ต้องการใช้ภายใน Function
ตัวอย่างพื้นฐาน
def func():
print(a) # ใช้ Global Variable
a = 10
func() # Output: 10
Variable a ประกาศนอก Function → Global Scope ใช้ได้ใน Function
Local vs Global Scope
a = 10 # Global
def func():
a = 5 # Local Variable (ชื่อเดียวกันแต่คนละตัว)
print("Inside function:", a) # 5
func()
print("Outside function:", a) # 10 (Global ไม่เปลี่ยน)
Variable a ภายใน Function เป็น Local Scope แยกจาก Global
Keyword global
ใช้เมื่อต้องการ ประกาศ/แก้ไข Global Variable ภายใน Function
โดยไม่มี global (Error)
def func():
a = 5
print("Inside:", a)
func()
print("Outside:", a) # NameError: name 'a' is not defined
ใช้ global Keyword
def func():
global a
a = 5
print("Inside function:", a) # 5
func()
print("Outside function:", a) # 5 (Global ถูกเปลี่ยน!)
Best Practices
| Situation | Recommendation |
|---|---|
| อ่าน Global | ใช้ได้เลย ไม่ต้อง global |
| เขียน/แก้ไข Global | ต้องใช้ global keyword |
| หลีกเลี่ยง Global | ส่งเป็น Parameter / Return ค่า / ใช้ Class |
ตัวอย่างแนะนำ: ใช้ Parameter/Return แทน Global
# ❌ ไม่ดี: ใช้ Global
counter = 0
def increment():
global counter
counter += 1
# ✅ ดีกว่า: ใช้ Parameter/Return
def increment(counter):
return counter + 1
counter = 0
counter = increment(counter)
counter = increment(counter)
print(counter) # 2
# ✅ หรือใช้ Class (Encapsulation)
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
c = Counter()
c.increment()
c.increment()
print(c.count) # 2
Global ใน Nested Functions (nonlocal)
def outer():
x = 10 # Enclosing Scope
def inner():
nonlocal x # ใช้ nonlocal ไม่ใช่ global
x = 20
inner()
print(x) # 20
outer()
Global Constants (Convention)
# Constants: UPPER_SNAKE_CASE
MAX_CONNECTIONS = 100
DEFAULT_TIMEOUT = 30
API_BASE_URL = "https://api.example.com"
def connect():
# อ่าน Constants ได้ ไม่ควรแก้ไข
print(f"Connecting to {API_BASE_URL}...")
# MAX_CONNECTIONS = 200 # ❌ Don't modify constants