收集任意数量的实参

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'] = first
5 profile['last_name'] = last
6 for key, value in user_info.items():
7 profile[key] = value
8 return profile
9
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 def unwrap(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

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

最新文章

  1. 小白学习MVC5+EF6遇到的问题一
  2. jQuery之ready源码分析
  3. 如何阻止SELECT * 语句
  4. My Game --线段数据
  5. 批处理与python代码混合编程的实现方法
  6. windows下安装PhpDocumentor(phpdoc)笔记
  7. The content of element type "package" must match "(result-types?,interceptors?...
  8. mysql 慢查询开启
  9. nicehair
  10. 使用MSBUILD 构建时出错 error MSB3086: Task could not find "sgen.exe" using the SdkToolsPath的解决方法
  11. 20160328 javaweb Cookie 小练习
  12. Mac OS X 程序员利器 – Homebrew安装与使用
  13. Android jar包混淆
  14. Delphi 获取北京时间(通过百度和timedate网站)
  15. 【JavaScript 】for 循环进化史
  16. Java中数组和集合的foreach操作编译后究竟是啥
  17. Java开源框架知识整理
  18. Confluence 6 自定义 Decorator 模板的宏和针对高级用户
  19. git help 机器翻译
  20. python07 函数式编程

热门文章

  1. shutdown 命令
  2. Charles-抓取https请求
  3. K8s 系列(三) - 如何配置 etcd https 证书?
  4. 密码学系列之:海绵函数sponge function
  5. vue随记
  6. 计算机网络 -- TCP/IP
  7. Jvm调优理论篇
  8. Docker系列(26)- 发布镜像到阿里云容器服务
  9. disruptor笔记之三:环形队列的基础操作(不用Disruptor类)
  10. PKI及SSL协议分析PKI及SSL协议分析