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

การส่งอาร์กิวเมนต์ใน Python: Pass by Value หรือ Pass by Reference?

Python ใช้กลไกที่เรียกว่า "Call-by-Object" หรือเรียกอีกอย่างว่า "Call by Object Reference" หรือ "Call by Sharing"

  • หากส่งอาร์กิวเมนต์ที่เป็น Immutable เช่น ตัวเลข, สตริง, Tuple ให้ฟังก์ชัน จะทำงานคล้าย Call-by-value
  • หากส่งอาร์กิวเมนต์ที่เป็น Mutable จะแตกต่างออกไป

พารามิเตอร์ทั้งหมดใน Python ถูกส่งแบบ Pass by Reference หมายถึง หากคุณเปลี่ยนสิ่งที่พารามิเตอร์อ้างอิงถึงภายในฟังก์ชัน การเปลี่ยนแปลงจะสะท้อนกลับไปยังฟังก์ชันที่เรียกด้วย

ตัวอย่าง

student = {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25}

def test(student_dict):
    new_students = {'alok': 30, 'Nevadan': 28}
    student_dict.update(new_students)
    print("Inside the function:", student_dict)
    return student_dict

test(student)
print("Outside the function:", student)

ผลลัพธ์

Inside the function: {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28}
Outside the function: {'Archana': 28, 'krishna': 25, 'Ramesh': 32, 'vineeth': 25, 'alok': 30, 'Nevadan': 28}

คำอธิบายเพิ่มเติม

  • Immutable objects (int, str, tuple): การส่งค่าเหมือน Pass by Value เพราะไม่สามารถเปลี่ยนแปลงค่าได้ ภายในฟังก์ชันจะสร้างออบเจกต์ใหม่แทน
  • Mutable objects (list, dict, set): การส่งค่าเป็น Pass by Reference จริงๆ การเปลี่ยนแปลงภายในฟังก์ชันจะส่งผลต่อออบเจกต์เดิม