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

后端 未结 6 925
长发绾君心
长发绾君心 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:56

    Adding to the other excellent posts.

    Sometimes you don't want to specify the number of arguments and want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method).

    def manyArgs1(args):
      print args.a, args.b #note args.c is not used here
    
    def manyArgs2(args):
      print args.c #note args.b and .c are not used here
    
    class Args: pass
    
    args = Args()
    args.a = 1
    args.b = 2
    args.c = 3
    
    manyArgs1(args) #outputs 1 2
    manyArgs2(args) #outputs 3
    

    Then you can do things like

    myfuns = [manyArgs1, manyArgs2]
    for fun in myfuns:
      fun(args)
    

提交回复
热议问题