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

Cách sử dụng *args và **kwargs trong Python

*args và **kwargs cho phép hàm nhận số lượng đối số biến đổi.

*args - Positional arguments tuple

def multiply(*args):
    result = 1
    for i in args:
        result *= i
    print(result)

multiply(3, 4)          # 12
multiply(10, 8)         # 80
multiply(2, 5, 6)       # 60
multiply(4, 5, 10, 9)   # 1800

**kwargs - Keyword arguments dict

def print_kwargs(**kwargs):
    print(kwargs)

print_kwargs(a='foo', b=10, c=True)
# {'a': 'foo', 'b': 10, 'c': True}

Kết hợp đầy đủ

def full_example(required, *args, default="value", **kwargs):
    print("required:", required)
    print("args:", args)
    print("default:", default)
    print("kwargs:", kwargs)

full_example(1, 2, 3, 4, default="custom", extra="hello")
# required: 1
# args: (2, 3, 4)
# default: custom
# kwargs: {'extra': 'hello'}

Unpacking khi gọi

args = (1, 2, 3)
kwargs = {'x': 10, 'y': 20}
func(*args, **kwargs)  # func(1, 2, 3, x=10, y=20)

Quy tắc thứ tự tham số

def func(pos_only, /, standard, *, kw_only, **kwargs): (Python 3.8+)