• 理解Python中的**,**kwargs


    1、**的作用

    首先是一个简单的例子,定义一个带有3个参数的函数

    def fun(a, b, c):
        print a, b, c

    这个函数可以使用多种方法进行调用

    fun(1,2,3)
    输出:1 2 3
    
     fun(1, b=4, c=6)
    输出:1 4 6               

    接下来使用**来进行函数调用,首先需要一个字典,就像使用*进行函数调用时需要列表或者元组一样

    d={'b':5, 'c':7}
    fun(1, **d)

    执行之后的输出为:1 5 7

    我们可以看到,在这里**的作用是将传入的字典进行unpack,然后将字典中的值作为关键词参数传入函数中。

    所以,在这里fun(1, **d)就等价于fun(1, b=5, c=7)

    更多的例子

    d={'c':3}
    fun(1,2,**d)   
    
    d={'a':7,'b':8,'c':9}
    fun(**d)
    #错误的例子
    d={'a':1, 'b':2, 'c':3, 'd':4}
    fun(**d)

    上面的代码会报错:

    TypeError: fun() got an unexpected keyword argument 'd'

    2、**kwargs的作用

    重新定义我们的fun函数

    def fun(a, **kwargs):
        print a, kwargs

    这个函数因为形参中只有一个a,所以只有一个positional argument。

    但是却有一个可以接收任意数量关键词参数的kwargs。

    使用**kwargs定义参数时,kwargs将会接收一个positional argument后所有关键词参数的字典。

    def fun(a, **kwargs):
        print "a is", a
        print "We expect kwargs 'b' and 'c' in this function"
        print "b is", kwargs['b']
        print "c is", kwargs['c']
    fun(1, b=3, c=5)

    输出是:

    a is 1                  
    We expect kwargs 'b' and 'c' in this function
    b is 3
    c is 5

    错误的调用:

    fun(1, b=3, d=5)
    a is 1
    We expect kwargs 'b' and 'c' in this function
    b is 3
    c is---------------------------------------------------------------------------
    KeyError                                  Traceback (most recent call last)
    
    xxxxx in <module>()
    xxxxx in fun(a, **kwargs)
    
    KeyError: 'c'
  • 相关阅读:
    Docker化高可用redis集群
    机器学习理论研究方法探讨
    (转载)iOS系统Crash文件分析方法
    ios 学习总结之动画(转)
    (转)iOS sqlite :truncate/delete/drop区分
    (转载)自定义 setDateFormat 显示格式
    (转载)IOS中UIScrollView的属性和委托方法
    vue 实现分页加载数据
    深入理解JQuery插件开发
    博客迁移到GitCafe
  • 原文地址:https://www.cnblogs.com/ruizhang3/p/6794615.html
Copyright © 2020-2023  润新知