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}
    这样得到的就是字典而不是元组
     
     
     
  • 相关阅读:
    c++ 文件读写模板
    sys和system用户的权限区别
    Oracle cmd 命令
    sqldeveloper的安装及其使用教程
    Oracle权限管理详解(2)
    Oracle权限管理详解(1)
    Oracle使用基础
    win7 64位操作系统中 Oracle 11g 安装教程(图解)
    MySQL cmd操作
    Linux下安装tomcat
  • 原文地址:https://www.cnblogs.com/swefii/p/10916682.html
Copyright © 2011-2022 走看看