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

Python Global และ Local Variables: ขอบเขตตัวแปรครบถ้วน

Variable (ตัวแปร) เป็นภาชนะเก็บข้อมูล ใน Python มี 2 ประเภทตาม Scope (ขอบเขต): Global และ Local

Global Variables

ประกาศ นอกฟังก์ชัน มี Global Scope เข้าถึงได้ทุกที่ในโปรแกรม รวมถึงภายในฟังก์ชัน

name = "Carlton Hernandez"  # Global

def print_name():
    print(name)  # เข้าถึง Global ได้

print_name()  # Carlton Hernandez

Local Variables

ประกาศ ภายในฟังก์ชัน มี Local Scope เข้าถึงได้เฉพาะในฟังก์ชันนั้นๆ

def print_name():
    name = "Georgia Anderson"  # Local
    print(name)

print_name()  # Georgia Anderson
print(name)   # NameError: name 'name' is not defined

ใช้ชื่อเดียวกัน Global และ Local

Local จะ "บัง" (Shadow) Global ภายในฟังก์ชัน

score = 5  # Global

def calculate_score():
    score = 10  # Local
    print("Final Score:", score)

calculate_score()  # Final Score: 10
print("Initial Score:", score)  # Initial Score: 5

Keyword global: แก้ไข Global ภายในฟังก์ชัน

ใช้ global ประกาศก่อนแก้ไข Global Variable ในฟังก์ชัน

name = "Bianca Peterson"

def set_name():
    global name
    name = "Bianca Lucinda Peterson"

set_name()
print(name)  # Bianca Lucinda Peterson

คำเตือน: ใช้ global น้อยที่สุด เพราะทำให้โค้ดยากต่อการ Debug และ Trace ค่า

สรุป

  • Global – ประกาศนอกฟังก์ชัน ใช้ได้ทุกที่
  • Local – ประกาศในฟังก์ชัน ใช้ได้แค่ในฟังก์ชัน
  • Shadowing – Local ชื่อเดียวกันบัง Global
  • global keyword – ให้ฟังก์ชันแก้ไข Global ได้ (ใช้ด้วยความระมัดระวัง)