args和* args作为函数输入的区别

时间:2019-07-06 22:17:22

标签: python

此问题是为了尝试了解星号(*)的作用。众所周知,*可以与args一起使用,以使该函数以后接受位置关键字。而且,它可以作为操作员来打开容器的包装。所以我的问题是:

如何知道其功能?

def product(*num):
    prod = 1
    for i in num:
        prod*= i
    return prod

def product2(num):
    prod = 1
    for i in num:
        prod*= i
    return prod

num = [2,3,5]

因此,当您使用不同的功能时,您将获得不同的结果。我只是想知道这里发生了什么?谢谢。

2 个答案:

答案 0 :(得分:2)

进行product(num)时,您会获得参数作为列表。因此,请逐步:

def product(*num):
    # num = [[2, 3, 5]]
    prod = 1
    for i in num:
        # i = [2, 3, 5]
        prod*= i    # prod = 1 * [2, 3, 5]
        # prod = [2, 3, 5]
    return prod

第二个函数product2(num)可以正常工作,计算得出1 * 2 * 3 * 5 = 30。

答案 1 :(得分:0)

*num意味着所有其他位置参数将被放入num中:

def test(*nums):
    print(nums)

test(1)            # (1,)
test(1, 2, 3, 4)   # (1, 2, 3, 4)

num*表示num中的所有值都将解压缩为位置参数。

def test(*nums):
    print(nums)

test([1]*)            # (1,)
test([1, 2, 3, 4]*)   # (1, 2, 3, 4)

在您的情况下,product将乘以其所有位置参数,而product2则期望一个参数包含某种带有数字的列表。

def product(*num):  # num = ([2, 3, 5],)
    prod = 1
    for i in num:   # i = [2, 3, 5]
        prod*= i    # prod = 1 * [2, 3, 5]
    return prod     # [2, 3, 5]

def product2(num):  # num = [2, 3, 5]
    prod = 1
    for i in num:   # i = 2; i = 3; i = 5
        prod*= i    # prod = 1 * 2; prod = 2 * 3; prod = 6 * 5
    return prod     # 30

num = [2, 3, 5]

如果您希望第一个工作,可以打开参数:

product(num*)  # equivalent to product(2, 3, 5)
相关问题