星号*在Python中是什么意思?

发布于 2021-02-02 23:16:35

*在Python中像在C中一样具有特殊含义吗?我在Python Cookbook中看到了这样的函数:

def get(self, *a, **kw)

你能向我解释一下还是指出我在哪里可以找到答案(Google将*解释为通配符,因此我找不到令人满意的答案)。

关注者
0
被浏览
101
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    假设知道位置和关键字参数是什么,下面是一些示例:

    范例1:

    # Excess keyword argument (python 2) example:
    def foo(a, b, c, **args):
        print "a = %s" % (a,)
        print "b = %s" % (b,)
        print "c = %s" % (c,)
        print args
    
    foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")
    

    如你在上面的示例中所见,函数a, b, c签名中仅包含参数foo。由于d和k不存在,因此将它们放入args字典。该程序的输出为:

    a = testa
    b = testb
    c = testc
    {'k': 'another_excess', 'd': 'excess'}
    

    范例2:

    # Excess positional argument (python 2) example:
    def foo(a, b, c, *args):
        print "a = %s" % (a,)
        print "b = %s" % (b,)
        print "c = %s" % (c,)
        print args
    
    foo("testa", "testb", "testc", "excess", "another_excess")
    

    在这里,由于我们正在测试位置参数,因此多余的参数必须在最后,并将*args它们打包成一个元组,因此该程序的输出为:

    a = testa
    b = testb
    c = testc
    ('excess', 'another_excess')
    

    你还可以将字典或元组解压缩为函数的参数:

    def foo(a,b,c,**args):
        print "a=%s" % (a,)
        print "b=%s" % (b,)
        print "c=%s" % (c,)
        print "args=%s" % (args,)
    
    argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
    foo(**argdict)
    

    输出:

    a=testa
    b=testb
    c=testc
    args={'excessarg': 'string'}
    

    def foo(a,b,c,*args):
        print "a=%s" % (a,)
        print "b=%s" % (b,)
        print "c=%s" % (c,)
        print "args=%s" % (args,)
    
    argtuple = ("testa","testb","testc","excess")
    foo(*argtuple)
    

    输出:

    a=testa
    b=testb
    c=testc
    args=('excess',)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看