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

วิธี Call Function ด้วย Argument List ใน Python

*args ใน parameter: pack arguments ที่เหลือเป็น list

*args ใน function call: unpack list เป็น arguments

ตัวอย่าง

def baz1(foo, *args):  # with star
    foo(*args)

def baz2(foo, args):   # without star
    foo(*args)

def foo2(x, y, z):
    print(x + y + z)

baz1(foo2, 2, 3, 4)
baz2(foo2, [2, 3, 4])

ผลลัพธ์

9
9

ทั้งสองวิธี args มีค่า [1,2,3] แต่วิธีเรียกต่างกัน