zoukankan      html  css  js  c++  java
  • python的*args与**kwargs

    1. *args 允许将一个非键值对的可变数量的参数列表(元组)传递给一个函数。

    >>> def add(*args):
    ...     return sum(args)
    ...
    >>> add(1,2,3,4)
    10
    >>> a = (1,2,3,4)
    >>> add(a) # 错误,等价于sum(((1,2,3,4),)),即将元组a与0相加
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in add
    TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
    >>> add(*a)
    10
    >>> sum(((1,2,3,4),))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

    2. **kwargs 允许将一个键值对的可变数量的参数字典传递给一个函数。

    >>> def add(**kwargs):
    ...     return sum(kwargs.values())
    ...
    >>> add(a=1,b=2,c=3)
    6

    综合:

    >>> def f(arg,*args,**kwargs):
    ...     print(arg)
    ...     print(args)
    ...     print(kwargs)
    ...
    >>> f(1,*(1,2,3,4),**{"a":1,"b":2,"c":3})
    1
    (1, 2, 3, 4)
    {'b': 2, 'c': 3, 'a': 1}
    >>> f(1,1,2,3,4,a=1,b=2,c=3) # 与上面效果一样

    调用时

    def func(a,b,c,d):
        print(a,b,c,d)
    
    args = (1,2,3,4)
    func(*args)
    1,2,3,4
    
    def func(a,b,c,d):
        print(a,b,c,d)
    
    kargs = {'a':1, 'b':2, 'c':3, 'd':4}
    func(**kargs)
    1,2,3,4
  • 相关阅读:
    servlet 传值和取值问题
    .net 获取存储过程返回值和Output输出参数值
    游标使用
    java中直接根据Date获取明天的日期
    Linux通配符与特殊符号知识大全
    zabbix监控
    KVM介绍 虚拟化简史
    GFS文件系统
    Oracle JOB定时器
    IDEA JSP 不能使用EL表达式
  • 原文地址:https://www.cnblogs.com/cymwill/p/8593180.html
Copyright © 2011-2022 走看看