Why use packed *args/**kwargs instead of passing list/dict?

后端 未结 3 1981
南笙
南笙 2021-01-31 21:12

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          


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-31 21:50

    *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)
    

    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)
    

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

    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.

提交回复
热议问题