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

后端 未结 3 1983
南笙
南笙 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 22:05

    This is kind of an old one, but to answer @DBrenko's queries about when *args and **kwargs would be required, the clearest example I have found is when you want a function that runs another function as part of its execution. As a simple example:

    import datetime
    
    def timeFunction(function, *args, **kwargs):
        start = datetime.datetime.now()
        output = function(*args, **kwargs)
        executionTime = datetime.datetime.now() - start
        return executionTime, output 
    

    timeFunction takes a function and the arguments for that function as its arguments. By using the *args, **kwargs syntax it isn't limited to specific functions.

提交回复
热议问题