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

Pass by Reference vs Value ใน Python

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

ตัวอย่าง

#!/usr/bin/python
# Function definition is here
def changeme(mylist):
    "This changes a passed list into this function"
    mylist.append([1,2,3,4]);
    print "Values inside the function: ", mylist
    return
# Now you can call changeme function
mylist = [10,20,30];
changeme(mylist);
print "Values outside the function: ", mylist

ผลลัพธ์ (Output)

ที่นี่ เราเก็บ reference ของอ็อบเจ็กต์ที่ส่งผ่านและ append ค่าในอ็อบเจ็กต์เดียวกัน ดังนั้นจะผลิตผลลัพธ์ดังนี้:

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

มีอีกตัวอย่างหนึ่งที่อาร์กิวเมนต์ถูกส่งผ่านแบบ reference และ reference ถูก overwrite ภายในฟังก์ชันที่ถูกเรียก

ตัวอย่าง

#!/usr/bin/python
# Function definition is here
def changeme(mylist):
    "This changes a passed list into this function"
    mylist = [1,2,3,4]; # This would assign new reference in mylist
    print "Values inside the function: ", mylist
    return
# Now you can call changeme function
mylist = [10,20,30];
changeme(mylist);
print "Values outside the function: ", mylist

ผลลัพธ์ (Output)

พารามิเตอร์ mylist เป็น local ต่อฟังก์ชัน changeme การเปลี่ยน mylist ภายในฟังก์ชันไม่ส่งผลต่อ mylist ฟังก์ชันนี้ไม่ทำอะไรและสุดท้ายจะผลิตผลลัพธ์ดังนี้:

Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]