What exactly do *args and **kwargs mean?

According to the Python documentation, from what it seems, it passes in a tuple of arguments.

def foo(hello, *args):
    print hello

    for each in args:
        print each

if __name__ == '__main__':
    foo("LOVE", ["lol", "lololol"])

This prints out:

LOVE
['lol', 'lololol']

How do you effectively use them?

推荐答案

Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.

For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:

def my_sum(*args):
    return sum(args)

It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.

You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.

The official Python documentation has a more in-depth look.

Python相关问答推荐

如何自动抓取以下CSV

Polars比较了两个预设-有没有方法在第一次不匹配时立即失败

比较两个数据帧并并排附加结果(获取性能警告)

当多个值具有相同模式时返回空

将jit与numpy linSpace函数一起使用时出错

max_of_three使用First_select、second_select、

有症状地 destruct 了Python中的regex?

PMMLPipeline._ fit()需要2到3个位置参数,但给出了4个位置参数

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

优化器的运行顺序影响PyTorch中的预测

实现神经网络代码时的TypeError

在不同的帧B中判断帧A中的子字符串,每个帧的大小不同

Pandas:计算中间时间条目的总时间增量

剪切间隔以添加特定日期

如何获得3D点的平移和旋转,给定的点已经旋转?

我可以不带视频系统的pygame,只用于游戏手柄输入吗?''

如何使用pytest在traceback中找到特定的异常

操作布尔值的Series时出现索引问题

将相应的值从第2列合并到第1列(Pandas )

两个名称相同但值不同的 Select 都会产生相同的值(discord.py)