代码之家  ›  专栏  ›  技术社区  ›  David Sykes

变量数的参数能否传递给函数?

  •  300
  • David Sykes  · 技术社区  · 15 年前

    以类似的方式在C或C++中使用VARARGS:

    fn(a, b)
    fn(a, b, c, d, ...)
    
    5 回复  |  直到 7 年前
        1
  •  383
  •   Community CDub    7 年前

    对。

    这很简单,如果忽略关键字参数,则可以使用:

    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)
    

    如您所见,Python将为您提供一个包含所有参数的元组。

    对于关键字参数,您需要接受它们作为单独的实际参数,如中所示。 Skurmedel's answer .

        2
  •  204
  •   Skurmedel    11 年前

    添加到展开日志:

    您也可以发送多个键值参数。

    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
    

    你可以把这两个混合起来:

    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
    

    它们必须按该顺序声明和调用,即函数签名必须是*args、**kwargs,并按该顺序调用。

        3
  •  12
  •   wizzwizz4    7 年前

    如果可以的话,skurmedel的代码是针对python 2的;要使其适应python 3,请更改 iteritems items 并将括号添加到 print . 这可以防止像我这样的初学者碰到: AttributeError: 'dict' object has no attribute 'iteritems' 在其他地方搜索(例如 Error “ 'dict' object has no attribute 'iteritems' ” when trying to use NetworkX's write_shp() )为什么会这样。

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

    还有:

    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
    
        4
  •  11
  •   Vladtn    13 年前

    加上其他优秀的职位。

    有时您不想指定参数的数目 想要为它们使用键(如果方法中没有使用字典中传递的一个参数,编译器会抱怨)。

    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
    

    然后你可以做像

    myfuns = [manyArgs1, manyArgs2]
    for fun in myfuns:
      fun(args)
    
        5
  •  2
  •   Rob shassss    11 年前
    def f(dic):
        if 'a' in dic:
            print dic['a'],
            pass
        else: print 'None',
    
        if 'b' in dic:
            print dic['b'],
            pass
        else: print 'None',
    
        if 'c' in dic:
            print dic['c'],
            pass
        else: print 'None',
        print
        pass
    f({})
    f({'a':20,
       'c':30})
    f({'a':20,
       'c':30,
       'b':'red'})
    ____________
    

    以上代码将输出

    None None None
    20 None 30
    20 red 30
    

    这就像用字典传递变量参数一样好。