zoukankan      html  css  js  c++  java
  • Python函数的带星号*参数

    1. 三种类型的函数参数

    def func(arg, *args, **kwargs):
        print (arg, type(arg))
        print (args, type(args))
        print (kwargs, type(kwargs))
    
    #arg     --  固定参数,必填
    #args    --  位置参数,可选
    #kwargs  --  关键字参数,可选

    如果同时出现(两两,或全部),三种类型的参数必须按序排列:

    (arg, *args, **kwargs)

    否则函数定义或者函数调用的时候都会出错。

    2. 固定参数arg

    >>> def func(arg):
    ...     print arg
    ... 
    >>> func()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: func() takes exactly 1 argument (0 given)
    >>> func(1)
    1

    3. 位置参数args

    1) 函数定义 -- tuple打包

    >>> def func1(*args):
    ...     print (args, type(args))
    ... 
    >>> func1()
    ((), <type 'tuple'>)
    >>> func1(1)
    ((1,), <type 'tuple'>)
    >>> func1(1,2,3)
    ((1, 2, 3), <type 'tuple'>)

    2) 函数调用 -- tuple解包

    >>> def func2(arg):
    ...     func1(*arg)
    ... 
    >>> func2()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: func2() takes exactly 1 argument (0 given)
    >>> func2(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in func2
    TypeError: func1() argument after * must be a sequence, not int
    >>> func2((1,))
    ((1,), <type 'tuple'>)
    >>> func2((1,2,3)) ((1, 2, 3), <type 'tuple'>)

    4. 关键字参数kwargs

    1) 函数定义 -- dict打包

    >>> def func1(**kwargs):
    ...     print (kwargs, type(kwargs))
    ... 
    >>> func1()
    ({}, <type 'dict'>)
    >>> func1(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: func1() takes exactly 0 arguments (1 given)
    >>> func1(a=1)
    ({'a': 1}, <type 'dict'>)
    >>> func1(a=1,b=2,c=3)
    ({'a': 1, 'c': 3, 'b': 2}, <type 'dict'>)

    2) 函数调用 -- dict解包

    >>> def func2(arg):
    ...     func1(**arg)
    ... 
    >>> func2()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: func2() takes exactly 1 argument (0 given)
    >>> func2(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in func2
    TypeError: func1() argument after ** must be a mapping, not int
    >>> func2(a=1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: func2() got an unexpected keyword argument 'a'
    >>> func2({'a': 1})
    ({'a': 1}, <type 'dict'>)
    >>> func2({'a': 1, 'b': 2, 'c': 3})
    ({'a': 1, 'c': 3, 'b': 2}, <type 'dict'>)
  • 相关阅读:
    windows 7系统搭建PHP网站环境
    本机搭建PHP环境全教程(图文)
    cmd不是内部命令解决方法
    [Tex学习笔记]章节用罗马字母编号
    丁伟岳院士逝世 享年70岁
    2014年度江西省青年科学家培养对象名单(共36名)
    Alexander Grothendieck去世了
    [詹兴致矩阵论习题参考解答]序言
    2014-2015第一学期听课安排
    一个老和尚的真言
  • 原文地址:https://www.cnblogs.com/russellluo/p/3137270.html
Copyright © 2011-2022 走看看