python参数:*和**

python支持函数从调用语句中收集任意数量的实参。在形参前可使用*和**。

1.*符号
例如:我们创建fruit函数的时候指定形参toppings前加*。

def fruit(*toppings):
print(toppings)

那我们在调用上面函数时,就可以穿任意多的参数。例如:


fruit("banana")
fruit("apple","orange")

输出如下所示:

('banana',)
('apple', 'orange')

形参名*toppings 中的星号让Python创建一个名为toppings 的空元组,并将收到的所有值都封装到这个元组中。在上面语句可加for循环。

def fruit(*toppings):
	print(type(toppings))
    for el in toppings:
         print('element: '+el)

fruit("banana")
fruit("apple", "orange")

输出如下:

<class 'tuple'>
element: banana
<class 'tuple'>
element: apple
element: orange

2.**符号
形参前加**,表示函数能够接受任意数量的键—值对。例如:

def build_profile(first1, last, **user_info):
    print(type(user_info))
    profile = {}
    profile['first_name'] = first1
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

输出:

<class 'dict'>
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

由上可知,**user_info定义了一个名为user_info的字典。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

永远不要矫情

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值