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

วิธีส่งอาร์กิวเมนต์แบบ Pass by Reference ในฟังก์ชัน Python

ใน Python อาร์กิวเมนต์ของฟังก์ชันจะถูกส่งแบบ "Call by Object Reference" เสมอ สามารถตรวจสอบได้ด้วยฟังก์ชัน id() ซึ่งจะคืนค่า identity (address ในหน่วยความจำ) ของออบเจ็กต์

ตัวอย่างยืนยัน

def foo(x):
    print("id of received argument", id(x))
    x.append("20")
    return x

a = ["10"]
print("id of argument before calling function", id(a))
b = foo(a)
print("id of returned object", id(b))
print(b)
print(a)

ผลลัพธ์

id of argument before calling function 1475589299912
id of received argument 1475589299912
id of returned object 1475589299912
['10', '20']
['10', '20']

ค่า id() ของ a, x ภายในฟังก์ชัน และ b เหมือนกันทุกตัว แสดงว่าเป็นออบเจ็กต์เดียวกัน การแก้ไข x ภายในฟังก์ชันส่งผลต่อ a ด้วย