zoukankan      html  css  js  c++  java
  • Python-15-收集参数

    允许用户提供任意数量的参数:
    def print_params(*params):
      print(params)
     
    >>> print_params('Testing')
    ('Testing',)
     
    >>> print_params(1, 2, 3)
    (1, 2, 3)
     
    赋值时带星号的变量收集多余的值。
     
    def print_params_2(title, *params):
      print(title)
      print(params)
     
    >>> print_params_2('Params:', 1, 2, 3)
    Params:
    (1, 2, 3)
     
    如果没有可供收集的参数, params将是一个空元组。
     
    >>> print_params_2('Nothing:')
    Nothing:
    ()
     
    带星号的参数也可以放在中间,这时需要使用名称来指定后续参数。
    >>> def in_the_middle(x, *y, z):
    ...   print(x, y, z)
    ...
    >>> in_the_middle(1, 2, 3, 4, 5, z=7)
    1 (2, 3, 4, 5) 7
    >>> in_the_middle(1, 2, 3, 4, 5, 7)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: in_the_middle() missing 1 required keyword-only argument: 'z'
     
    星号不会收集关键字参数。
    >>> print_params_2('Hmm...', something=42)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: print_params_2() got an unexpected keyword argument 'something'
    要收集关键字参数,可使用两个星号。
    >>> def print_params_3(**params):
    ...   print(params)
    ...
    >>> print_params_3(x=1, y=2, z=3)
    {'z': 3, 'x': 1, 'y': 2}
    这样得到的就是字典而不是元组
     
     
     
  • 相关阅读:
    Java数据类型转换
    github的入门使用
    移动端的头部标签和meta
    gulp&gulp-less
    前端工程筹建NodeJs+gulp+bower
    jQuery 遍历
    JavaScript for...in 语句
    console.log在线调试
    sessionStorage html5客户端本地存储之sessionStorage及storage事件
    一个页面从输入url到加载完成的过程都发生了什么,请详细说明
  • 原文地址:https://www.cnblogs.com/swefii/p/10916682.html
Copyright © 2011-2022 走看看