*args 和 **kwargs 是什么意思?

问题描述:

*args**kwargs 到底是什么意思?

What exactly do *args and **kwargs mean?

根据 Python 文档,从表面上看,它传入了一个参数元组.

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

打印出来:

LOVE
['lol', 'lololol']

你如何有效地使用它们?

How do you effectively use them?

*args 和/或 **kwargs 作为函数定义的参数列表中的最后一项允许该函数接受任意数量的参数和/或关键字参数.

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.

您实际上不必将它们称为 argskwargs,这只是一个约定.*** 发挥了神奇的作用.

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

官方 Python 文档有更深入的看.

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