为什么使用打包的 *args/**kwargs 而不是传递列表/字典? [英] Why use packed *args/**kwargs instead of passing list/dict?

查看:64
本文介绍了为什么使用打包的 *args/**kwargs 而不是传递列表/字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不知道一个函数将传递多少个参数,我可以使用参数打包来编写函数:

If I don't know how many arguments a function will be passed, I could write the function using argument packing:

def add(factor, *nums):
    """Add numbers and multiply by factor."""
    return sum(nums) * factor

或者,我可以通过传递数字列表作为参数来避免参数打包:

Alternatively, I could avoid argument packing by passing a list of numbers as the argument:

def add(factor, nums):
    """Add numbers and multiply by factor.

    :type factor: int
    :type nums: list of int
    """
    return sum(nums) * factor

与传递数字列表相比,使用参数打包 *args 是否有优势?或者有没有更合适的情况?

Is there an advantage to using argument packing *args over passing a list of numbers? Or are there situations where one is more appropriate?

推荐答案

*args/**kwargs 有它的优势,一般在你希望能够的情况下传递未打包的数据结构,同时保留处理打包数据结构的能力.Python 3 的 print() 就是一个很好的例子.

*args/**kwargs has its advantages, generally in cases where you want to be able to pass in an unpacked data structure, while retaining the ability to work with packed ones. Python 3's print() is a good example.

print('hi')
print('you have', num, 'potatoes')
print(*mylist)

对比一下如果 print() 只采用一个压缩结构然后在函数中扩展它会是什么样子:

Contrast that with what it would be like if print() only took a packed structure and then expanded it within the function:

print(('hi',))
print(('you have', num, 'potatoes'))
print(mylist)

在这种情况下,*args/**kwargs 非常方便.

In this case, *args/**kwargs comes in really handy.

当然,如果您希望函数始终传递包含在数据结构中的多个参数,如 sum()str.join() 所做的那样,它省略 * 语法可能更有意义.

Of course, if you expect the function to always be passed multiple arguments contained within a data structure, as sum() and str.join() do, it might make more sense to leave out the * syntax.

这篇关于为什么使用打包的 *args/**kwargs 而不是传递列表/字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆