Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách gọi function với argument list trong Python?

def baz1(foo, *args):

* bên cạnh args nghĩa là "take the rest of the parameters given and put them in a list called args".

Trong dòng:

foo(*args)

* bên cạnh args ở đây nghĩa là "take this list called args and 'unwrap' nó vào rest of the parameters."

Trong foo2, list được passed explicitly, nhưng trong cả hai wrappers args chứa list [1,2,3].

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])

OUTPUT

9
9