Python:两种魔法参数 *args和**kwargs的用法

首先定义一个带有两个常规参数的求和函数,传入一个参数arg1,arg2

def sum(arg1, arg2):
    print(arg1 + arg2)
sum(2, 3)

那如果要求5个参数求和,那就需要更改函数内部代码,使其变得更加累赘。所以这时候我们就可以通过传入魔法参数去处理。

def sum(*args):
	print(args)
    print(type(args)) # 元组类型
    su = 0
    for arg in args:
        su += arg
    print(su)
sum(2,3,4)
sum(2,3,4,5)
sum(2,3,4,5,6)
#结果
(2, 3, 4)
<class 'tuple'>
9
(2, 3, 4, 5)
<class 'tuple'>
14
(2, 3, 4, 5, 6)
<class 'tuple'>
20

这样无论我们传入多少参数都可以在不改变代码的情况下输出想要的结果,而且传进去的参数都被转化成tuple类型放在一起。
此外,我们还可以通过传将listtupleset类型作为参数传入函数,但是传入参数之前必须要在传入的引用变量前加*

def sum(*args):
    print(args)
    print(type(args))
    su = 0
    for arg in args:
        su += arg
    print(su)
tuple_ = (1,2,3)
list_ = [1,2,3]
set_ = {1,2,3}
sum(*tuple_)
sum(*list_)
sum(*set_)

另外再介绍另一种魔法参数**kwargs,直接演示一个示例吧~

def daily_food(arg, *args, **kwargs):
    print(f"this is a common arg: {arg}")
    print(args)
    print(kwargs)
daily_food("大鸡腿", 2, 3, food1="apple", food2="ice cream")
# 输出结果
this is a common arg: 大鸡腿
(2, 3)
{'food1': 'apple', 'food2': 'ice cream'}

从上面我们可以看到,daily_food这个函数接收一个普通变量和两个魔法变量,首先接收一个普通变量,然后剩下的变量一部分会打包成元组传入函数,另一部分打包成字典传入函数。
注意!参数的顺序不能出错,普通变量只能放在魔法变量的后面,否则会报错!(common_arg, *args, **kwargs)

def daily_food(*args, arg, **kwargs):
    print(f"this is a common arg: {arg}")
    print(args)
    print(kwargs)
daily_food("大鸡腿", 2, 3, food1="apple", food2="ice cream")
# 结果
TypeError                                 Traceback (most recent call last)
<ipython-input-78-2f6d40a25eec> in <module>
      3     print(args)
      4     print(kwargs)
----> 5 daily_food("大鸡腿", 2, 3, food1="apple", food2="ice cream")

TypeError: daily_food() missing 1 required keyword-only argument: 'arg'

同样,我们可以把字典作为输入传给**kwargs

def daily_food(arg, *args, **kwargs):
    print(f"this is a common arg: {arg}")
    print(args)
    print(kwargs)

food = {"food1": "apple", "food2": "ice cream"}
daily_food("大鸡腿", 2, 3, **food) # 需要再变量前加 **
# 结果
this is a common arg: 大鸡腿
(2, 3)
{'food1': 'apple', 'food2': 'ice cream'}

假如函数接收的参数过多,这两个魔法方法就能够优雅的简化我们的代码。
(说完了,放一张美食图:嘿嘿嘿嘿嘿~)
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值