该*指定参数和** kwargs是通过一种方法多参数的函数。它们允许将可变数量的参数传递给函数。但是,请注意,不必仅将变量命名为* args或** kwargs。仅*是重要的。我们也可以将变量命名为* var或** named_vars。
* args用于将非关键字的可变长度参数列表发送到函数。
示例
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def test_args(arg1, *argv): ... print("first argument :{}".format(arg1)) ... for arg in argv: ... print("argument received :{}".format(arg)) ... >>> test_args('test1', 'test2', 'test3') first argument :test1 argument received :test2 argument received :test3 >>>
** kwargs允许将关键字可变长度参数传递给方法。该** kwargs是为了处理使用的函数命名参数。
示例
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def welcome_names(**kwargs): ... if kwargs: ... for key, value in kwargs.items(): ... print("{} = {}".format(key, value)) ... >>> welcome_names(name="include_help") name = include_help >>>
示例
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def test_multiple_args(arg1, arg2, arg3): ... print(arg1) ... print(arg2) ... print(arg3) ... >>>
现在,让我们使用* args作为上述函数,
>>> args = ['test1', 1,2] >>> test_multiple_args(*args) test1 1 2
现在,使用** kwargs
>>> kwargs = {"arg3": 3, "arg2": "two","arg1":5} >>> test_multiple_args(**kwargs) 5 two 3 >>>