python 参数收集_python收集参数与解包

收集任意数量的实参

def make_pizza(*toppings):"""打印顾客点的所有配料"""

print(toppings)

make_pizza('pepperoni')

make_pizza('mushrooms', 'green peppers', 'extra cheese')

形参名*toppings 中的星号让Python创建一个名为toppings 的空元组,并将收到的所有值都封装到这个元组中。注意,Python将实参封装到一个元组中,即便函数只收到一个值也如此:

('pepperoni',)

('mushrooms', 'green peppers', 'extra cheese')

传递任意数量的关键字实参

1 def build_profile(first, last, **user_info):2 """Build a dictionary containing everything we know about a user."""

3 profile ={}4 profile['first_name'] =first5 profile['last_name'] =last6 for key, value inuser_info.items():7 profile[key] =value8 returnprofile9

10 user_profile = build_profile('albert', 'einstein',11 location='princeton',12 field='physics')13 print(user_profile)

形参**user_info 中的两个星号让Python创建一个名为user_info 的空字典,并将收到的所有名称—值对都封装到这个字典中。

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

解包参数

1. 我们可以给函数unwrap传递含有四个参数的元组,并且让python自动将这个元组解包成相应的参数.

2.类似的,在函数调用时,** 会以键/值对的形式把一个字典解包为独立的关键字参数.

1 defunwrap(a, b, c, d):2 print(a, b, c, d)3

4 unwrap(1, 2, 3, 4) #打印: 1 2 3 4

5

6 args = (1, 2, 3, 4)7 unwrap(*args) #打印: 1 2 3 4

8

9 args_dict = {'a':1, "b":2, "c":3, "d":4}10 unwrap(**args_dict) #打印: 1 2 3 4

别混淆函数头部和函数调用时*/**的语法:在函数头部,它意味着收集任意多的参数,而在函数调用时,它能解包任意多的参数.在两种情况下,一个星号代表基于位置的参数,两个星号代表关键字参数.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值