Python中的多功能参数

The *args and **kwargs is an approach to pass multiple arguments to a function. They allow to pass a variable number of arguments to a function. However, please note it is not necessary to name the variables as *args or **kwargs only. Only the * is important. We could also name the variables as *var or **named_vars.

* args和** kwargs是一种将多个参数传递给函数的方法 。 它们允许将可变数量的参数传递给函数。 但是,请注意,不必将变量仅命名为* args** kwargs 。 仅*是重要的。 我们也可以将变量命名为* var** named_vars

* args的用法 (Usage of *args)

*args is used to send a non-keyworded variable length argument list to a function.

* args用于将非关键字的可变长度参数列表发送到函数

Example:

例:

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的用法 (Usage of **kwargs)

**kwargs allows to pass keyworded variable length arguments to a method. The **kwargs is used in order to handle named arguments in a function.

** kwargs允许将关键字可变长度参数传递给方法** kwargs用于处理函数中的命名参数

Example:

例:

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

Example:

例:

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

Now, let's use *args for the above function,

现在,我们将* args用于上述功能,

>>> args = ['test1', 1,2]
>>> test_multiple_args(*args)
test1
1
2

Now, using **kwargs,

现在,使用** kwargs

>>> kwargs = {"arg3": 3, "arg2": "two","arg1":5}
>>> test_multiple_args(**kwargs)
5
two
3
>>>


翻译自: https://www.includehelp.com/python/multiple-function-arguments.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值