Can a variable number of arguments be passed to a function?

后端 未结 6 934
长发绾君心
长发绾君心 2020-11-22 00:32

In a similar way to using varargs in C or C++:

fn(a, b)
fn(a, b, c, d, ...)
6条回答
  •  轮回少年
    2020-11-22 00:45

    Yes. You can use *args as a non-keyword argument. You will then be able to pass any number of arguments.

    def manyArgs(*arg):
      print "I was called with", len(arg), "arguments:", arg
    
    >>> manyArgs(1)
    I was called with 1 arguments: (1,)
    >>> manyArgs(1, 2, 3)
    I was called with 3 arguments: (1, 2, 3)
    

    As you can see, Python will unpack the arguments as a single tuple with all the arguments.

    For keyword arguments you need to accept those as a separate actual argument, as shown in Skurmedel's answer.

提交回复
热议问题