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

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

    Adding to unwinds post:

    You can send multiple key-value args too.

    def myfunc(**kwargs):
        # kwargs is a dictionary.
        for k,v in kwargs.iteritems():
             print "%s = %s" % (k, v)
    
    myfunc(abc=123, efh=456)
    # abc = 123
    # efh = 456
    

    And you can mix the two:

    def myfunc2(*args, **kwargs):
       for a in args:
           print a
       for k,v in kwargs.iteritems():
           print "%s = %s" % (k, v)
    
    myfunc2(1, 2, 3, banan=123)
    # 1
    # 2
    # 3
    # banan = 123
    

    They must be both declared and called in that order, that is the function signature needs to be *args, **kwargs, and called in that order.

提交回复
热议问题