• ython的星号(*、**)的作用


    (一)函数的可变参数

      当函数的参数前面有一个星号*的时候表示这是一个可变的位置参数,两个星号**表示是可变的关键字参数。这样我们可以传递任意个参数

    def foo(*args, **kwarg):
        for item in args:
            print item
    
        for k,v in kwarg.items():
            print k,v
        print 30*'='
    if __name__ == '__main__':
        foo(1, 2, 3, a=4, b=5)
        foo(2, 3, a=4, b=5, c=1)
    1
    2
    3
    a 4
    b 5
    ==============================
    2
    3
    a 4
    c 1
    b 5
    ==============================

    2. unpack参数

        星号*把序列/集合解包(unpack)成位置参数,两个星号**把字典解包成关键字参数。下面通过示例来进一步加深理解:

    def foo(*args, **kwarg):
        for item in args:
            print item
        for k,v in kwarg.items():
            print k,v
        print 30*'='
    
    if __name__ == '__main__':
        #foo(1, 2, 3, a=4, b=5)
        #foo(2, 3, a=4, b=5, c=1)
        v = (1, 2, 4)
        v2 = [11, 15, 23]
        d = {'a':1, 'b':12}
        foo(v, d)
        foo(*v, **d)
        foo(v2, d)
        foo(*v2, **d)

    输出:

    (1, 2, 4)
    {'a': 1, 'b': 12}
    ==============================
    1
    2
    4
    a 1
    b 12
    ==============================
    [11, 15, 23]
    {'a': 1, 'b': 12}
    ==============================
    11
    15
    23
    a 1
    b 12
    ==============================
    
    

      

    3. 几个注意点

    可变位置参数*args是一个元组,是不可修改的。

    >>> def foo(*args):
    ...     args[0] = 5
    ... 
    >>> foo(1, 2, 3)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in foo
    TypeError: 'tuple' object does not support item assignment
    >>> l = [1, 2, 3]
    >>> foo(*l)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in foo
    TypeError: 'tuple' object does not support item assignment

    无论我们怎么传入参数,args都是一个tuple类型,不能进行修改。

    对于字典类型的如果只使用一个型号*那么传入的只是字典的键。

    >>> def foo2(*args, **kwarg):
    ...     print args, kwarg
    ... 
    >>> d = {'a':1, 'b':2, 'c':3}
    >>> foo2(*d)
    ('a', 'c', 'b') {}
    >>> foo2(**d)
    () {'a': 1, 'c': 3, 'b': 2}
    

     

  • 相关阅读:
    VS.NET的新用途
    ASP.NET缓存引起的问题
    增加了查看最新回复功能
    高级浏览功能可以使用了
    转载JGTM'2004 [MVP]的文章
    首页文章字数统计改进
    请推荐好的工作流产品
    不错的工具:Reflector for .NET
    寻找文件同步软件
    javascript引起博客园首页不能显示问题说明
  • 原文地址:https://www.cnblogs.com/yc3110/p/13293450.html
Copyright © 2020-2023  润新知