DBe*_*nko 11 python parameter-passing kwargs
如果我不知道函数将传递多少个参数,我可以使用参数包装来编写函数:
def add(factor, *nums):
"""Add numbers and multiply by factor."""
return sum(nums) * factor
Run Code Online (Sandbox Code Playgroud)
或者,我可以通过传递一个数字列表作为参数来避免参数打包:
def add(factor, nums):
"""Add numbers and multiply by factor.
:type factor: int
:type nums: list of int
"""
return sum(nums) * factor
Run Code Online (Sandbox Code Playgroud)
使用参数打包而*args不是传递数字列表是否有优势?或者是否存在更合适的情况?
*args/ **kwargs有其优点,通常是在您希望能够传递解压缩的数据结构的情况下,同时保留使用打包数据结构的能力.Python 3 print()就是一个很好的例子.
print('hi')
print('you have', num, 'potatoes')
print(*mylist)
Run Code Online (Sandbox Code Playgroud)
对比如果print()只采用打包结构然后在函数内扩展它会是什么样的:
print(('hi',))
print(('you have', num, 'potatoes'))
print(mylist)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,*args/ **kwargs非常方便.
当然,如果你希望函数总是传递给数据结构中包含的多个参数sum(),str.join()那么,省略*语法可能更有意义.
| 归档时间: |
|
| 查看次数: |
3259 次 |
| 最近记录: |