代码之家  ›  专栏  ›  技术社区  ›  Zango

Python函数的参数长度?[副本]

  •  8
  • Zango  · 技术社区  · 15 年前


    How to find out the arity of a method in Python

    def sum(a,b,c):
        return a + b + c
    

    我想得到“sum”函数参数的长度。
    像这样的:返回3的某个函数(sum)
    如何在Python中完成?

    更新:

    def funct(anotherFunct, **args): 
    

    我需要确认:

    if(len(args) != anotherFuct.func_code.co_argcount):
        return "error"
    
    3 回复  |  直到 9 年前
        1
  •  5
  •   user JaredPar    12 年前

    如果你的方法名是 sum 然后 sum.func_code.co_argcount 会给你一些论据。

        2
  •  14
  •   RichieHindle    15 年前

    这个 inspect 模块是你的朋友;特别是 inspect.getargspec 它提供有关函数参数的信息:

    >>> def sum(a,b,c):
    ...     return a + b + c
    ...
    >>> import inspect
    >>> argspec = inspect.getargspec(sum)
    >>> print len(argspec.args)
    3
    

    argspec 还包含可选参数和关键字参数的详细信息,在您的示例中,您没有这些参数,但值得了解:

    >>> print argspec
    ArgSpec(args=['a', 'b', 'c'], varargs=None, keywords=None, defaults=None)
    
        3
  •  2
  •   Ned Batchelder    15 年前
    import inspect
    
    print len(inspect.getargspec(sum)[0])