【问题标题】:Difference call function with asterisk parameter and without带星号参数和不带星号参数的差异调用函数
【发布时间】:2015-07-03 02:37:15
【问题描述】:

我知道星号在 Python 中的函数定义中是什么意思。

不过,我经常在调用带有以下参数的函数时看到星号:

def foo(*args, **kwargs):
    first_func(args, kwargs)
    second_func(*args, **kwargs)

第一次和第二次函数调用有什么区别?

【问题讨论】:

标签: python function-parameter argument-unpacking


【解决方案1】:

args = [1,2,3]:

func(*args) == func(1,2,3) - 变量作为参数从列表(或任何其他序列类型)中解包出来

func(args) == func([1,2,3]) - 列表通过

kwargs = dict(a=1,b=2,c=3):

func(kwargs) == func({'a':1, 'b':2, 'c':3}) - 字典通过

func(*kwargs) == func(('a','b','c')) - 字典键的元组(随机顺序)

func(**kwargs) == func(a=1,b=2,c=3) - (key, value) 作为命名参数从 dict(或任何其他映射类型)中解包出来

【讨论】:

  • 一个不错的简单答案。谢谢。
  • 非常好的答案:+1!您能否添加并解释func(*kwarg) 的案例?
  • 好极了,解释得很好。这真的不难,但很多人写了 5 页以上的内容
【解决方案2】:

不同之处在于参数是如何传递给被调用函数的。当您使用* 时,参数会被解包(如果它们是列表或元组)— 否则,它们只是按原样传入。

这里是一个不同的例子:

>>> def add(a, b):
...   print a + b
...
>>> add(*[2,3])
5
>>> add([2,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes exactly 2 arguments (1 given)
>>> add(4, 5)
9

当我在参数前面加上* 时,它实际上将列表解压缩为两个单独的参数,它们作为ab 传递到add。没有它,它只是作为单个参数传入列表。

字典和** 也是如此,只是它们作为命名参数而不是有序参数传入。

>>> def show_two_stars(first, second='second', third='third'):
...    print "first: " + str(first)
...    print "second: " + str(second)
...    print "third: " + str(third)
>>> show_two_stars('a', 'b', 'c')
first: a
second: b
third: c
>>> show_two_stars(**{'second': 'hey', 'first': 'you'})
first: you
second: hey
third: third
>>> show_two_stars({'second': 'hey', 'first': 'you'})
first: {'second': 'hey', 'first': 'you'}
second: second
third: third

【讨论】:

  • 感谢您的详细回答。这对我很有帮助。
【解决方案3】:
def fun1(*args):
    """ This function accepts a non keyworded variable length argument as a parameter.
    """
    print args        
    print len(args)


>>> a = []

>>> fun1(a)
([],)
1
# This clearly shows that, the empty list itself is passed as a first argument. Since *args now contains one empty list as its first argument, so the length is 1
>>> fun1(*a)
()
0
# Here the empty list is unwrapped (elements are brought out as separate variable length arguments) and passed to the function. Since there is no element inside, the length of *args is 0
>>>

【讨论】:

  • 我认为如果您向a添加一些值,您的答案会更清楚
  • 这个例子是为了展示解包 args 的工作方式。如果您将一个元素添加到 'a' 并传递给 args 而不解包,则 args 的长度将为 1。对于第一种情况,它将是 (['some val'],),对于第二种情况,它将是('一些 val',)
  • 如果您将前面评论中的示例添加到您的答案中,看起来会很棒。 :-)
猜你喜欢
  • 1970-01-01
  • 2019-11-30
  • 2021-09-21
相关资源
最近更新 更多