星号*在Python中是什么意思? [重复]

本文翻译自:What does asterisk * mean in Python? [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

Does * have a special meaning in Python as it does in C? *在Python中像在C中一样具有特殊含义吗? I saw a function like this in the Python Cookbook: 我在Python Cookbook中看到了这样的函数:

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

Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find a satisfactory answer). 您能向我解释一下还是指出在哪里可以找到答案(Google将*解释为通配符,因此我找不到令人满意的答案)。

Thank you very much. 非常感谢你。


#1楼

参考:https://stackoom.com/question/1gFX/星号-在Python中是什么意思-重复


#2楼

See Function Definitions in the Language Reference. 请参见《语言参考》中的“ 函数定义 ”。

If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. 如果存在形式*identifier ,则将其初始化为接收任何多余位置参数的元组,默认为空元组。 If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary. 如果存在**identifier形式,则它将初始化为一个新字典,该字典将接收任何多余的关键字参数,默认为一个新的空字典。

Also, see Function Calls . 另请参见函数调用

Assuming that one knows what positional and keyword arguments are, here are some examples: 假设知道位置和关键字参数是什么,下面是一些示例:

Example 1: 范例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")

As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. 如您在上面的示例中所见,在foo函数的签名中我们只有参数a, b, c Since d and k are not present, they are put into the args dictionary. 由于dk不存在,因此将它们放入args字典中。 The output of the program is: 该程序的输出为:

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

Example 2: 范例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")

Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is: 在这里,由于我们正在测试位置参数,所以多余的参数必须在最后,并且*args将它们打包到一个元组中,因此该程序的输出为:

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

You can also unpack a dictionary or a tuple into arguments of a function: 您还可以将字典或元组解压缩为函数的参数:

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)

Prints: 印刷品:

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

And

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)

Prints: 印刷品:

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

#3楼

A single star means that the variable 'a' will be a tuple of extra parameters that were supplied to the function. 单颗星意味着变量“ a”将是提供给函数的额外参数的元组。 The double star means the variable 'kw' will be a variable-size dictionary of extra parameters that were supplied with keywords. 双星表示变量“ kw”将是带有关键字的额外参数的可变大小词典。

Although the actual behavior is spec'd out, it still sometimes can be very non-intuitive. 尽管已说明了实际的行为,但有时仍然可能非常不直观。 Writing some sample functions and calling them with various parameter styles may help you understand what is allowed and what the results are. 编写一些示例函数并使用各种参数样式进行调用可以帮助您了解允许的结果以及结果。

def f0(a)
def f1(*a)
def f2(**a)
def f3(*a, **b)
etc...

#4楼

I only have one thing to add that wasn't clear from the other answers (for completeness's sake). 我只有一件事要补充,从其他答案中看不出来(出于完整性考虑)。

You may also use the stars when calling the function. 您也可以在调用函数时使用星号。 For example, say you have code like this: 例如,假设您有如下代码:

>>> def foo(*args):
...     print(args)
...
>>> l = [1,2,3,4,5]

You can pass the list l into foo like so... 您可以像这样将列表l传递给foo ...

>>> foo(*l)
(1, 2, 3, 4, 5)

You can do the same for dictionaries... 您可以对字典执行相同的操作...

>>> def foo(**argd):
...     print(argd)
...
>>> d = {'a' : 'b', 'c' : 'd'}
>>> foo(**d)
{'a': 'b', 'c': 'd'}

#5楼

I find * useful when writing a function that takes another callback function as a parameter: 在编写将另一个回调函数作为参数的函数时,我发现*很有用:

def some_function(parm1, parm2, callback, *callback_args):
    a = 1
    b = 2
    ...
    callback(a, b, *callback_args)
    ...

That way, callers can pass in arbitrary extra parameters that will be passed through to their callback function. 这样,调用者可以传入将传递给其回调函数的任意额外参数。 The nice thing is that the callback function can use normal function parameters. 令人高兴的是,回调函数可以使用常规函数参数。 That is, it doesn't need to use the * syntax at all. 也就是说,它根本不需要使用*语法。 Here's an example: 这是一个例子:

def my_callback_function(a, b, x, y, z):
    ...

x = 5
y = 6
z = 7

some_function('parm1', 'parm2', my_callback_function, x, y, z)

Of course, closures provide another way of doing the same thing without requiring you to pass x, y, and z through some_function() and into my_callback_function(). 当然,闭包提供了另一种执行相同操作的方式,而无需您将x,y和z通过some_function()传递到my_callback_function()中。


#6楼

All of the above answers were perfectly clear and complete, but just for the record I'd like to confirm that the meaning of * and ** in python has absolutely no similarity with the meaning of similar-looking operators in C. 以上所有答案都是非常清晰和完整的,但仅作记录,我想确认python中*和**的含义与C语言中类似运算符的含义绝对没有相似之处。

They are called the argument-unpacking and keyword-argument-unpacking operators. 它们被称为参数拆包和关键字参数拆包运算符。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值