我如何才能找到一个Python函数的参数的数量?我需要知道它有多少普通参数和多少命名参数。
例子:
def someMethod(self, arg1, kwarg1=None):
pass
这个方法有2个参数和1个命名参数。
我如何才能找到一个Python函数的参数的数量?我需要知道它有多少普通参数和多少命名参数。
例子:
def someMethod(self, arg1, kwarg1=None):
pass
这个方法有2个参数和1个命名参数。
当前回答
import inspect
inspect.getargspec(someMethod)
查看inspect模块
其他回答
你可以通过(将"function"替换为你的函数名)获得参数的数量:
function.__code__.co_argcount ## 2
参数的名称为:
function.__code__.co_varnames ## ('a', 'b')
import inspect
inspect.getargspec(someMethod)
查看inspect模块
inspect.getargspec ()
Get the names and default values of a function’s arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). args is a list of the argument names (it may contain nested lists). varargs and varkw are the names of the * and ** arguments or None. defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args. Changed in version 2.6: Returns a named tuple ArgSpec(args, varargs, keywords, defaults).
看到can-you-list-the-keyword-arguments-a-python-function-receives。
someMethod.func_code.co_argcount
或者,如果当前函数名未确定:
import sys
sys._getframe().func_code.co_argcount
In:
import inspect
class X:
def xyz(self, a, b, c):
return
print(len(inspect.getfullargspec(X.xyz).args))
Out:
4
注意:如果xyz不在类X中,并且没有“self”,只有“a, b, c”,那么它将打印3。
对于3.5以下的python,您可能需要替换inspect。通过检查获得全部规格。在上面的代码中获取目标规格。