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

问题描述

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

范例1:

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

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

  1. a = testa
  2. b = testb
  3. c = testc
  4. {'k': 'another_excess', 'd': 'excess'}

范例2:

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

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

  1. a = testa
  2. b = testb
  3. c = testc
  4. ('excess', 'another_excess')

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

  1. def foo(a,b,c,**args):
  2. print "a=%s" % (a,)
  3. print "b=%s" % (b,)
  4. print "c=%s" % (c,)
  5. print "args=%s" % (args,)
  6. argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
  7. foo(**argdict)

输出

  1. a=testa
  2. b=testb
  3. c=testc
  4. args={'excessarg': 'string'}

  1. def foo(a,b,c,*args):
  2. print "a=%s" % (a,)
  3. print "b=%s" % (b,)
  4. print "c=%s" % (c,)
  5. print "args=%s" % (args,)
  6. argtuple = ("testa","testb","testc","excess")
  7. foo(*argtuple)

输出

  1. a=testa
  2. b=testb
  3. c=testc
  4. args=('excess',)

解决方法

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

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

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

猜你在找的技术问答相关文章

如何检查配对的蓝牙设备是打印机还是扫描仪(Android)
是否允许实体正文进行HTTP DELETE请求?
如何将ZipInputStream转换为InputStream?
java.util.logging Java 8中的变量
PowerMockito.doReturn返回null
Java中的RESTful调用
Swing / Java:如何正确使用getText和setText字符串
特殊字符和重音字符
Android Studio中的ndk.dir错误
错误“找不到主类”