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

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

    If I may, Skurmedel's code is for python 2; to adapt it to python 3, change iteritems to items and add parenthesis to print. That could prevent beginners like me to bump into: AttributeError: 'dict' object has no attribute 'iteritems' and search elsewhere (e.g. Error “ 'dict' object has no attribute 'iteritems' ” when trying to use NetworkX's write_shp()) why this is happening.

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

    and:

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

提交回复
热议问题