我如何才能找到一个Python函数的参数的数量?我需要知道它有多少普通参数和多少命名参数。

例子:

def someMethod(self, arg1, kwarg1=None):
    pass

这个方法有2个参数和1个命名参数。


当前回答

你可以通过(将"function"替换为你的函数名)获得参数的数量:

function.__code__.co_argcount ## 2

参数的名称为:

function.__code__.co_varnames ## ('a', 'b')

其他回答

除此之外,我还看到help()函数在大多数情况下确实有帮助

例如,它给出了它所接受的参数的所有细节。

help(<method>)

给出以下内容

method(self, **kwargs) method of apiclient.discovery.Resource instance
Retrieves a report which is a collection of properties / statistics for a specific customer.

Args:
  date: string, Represents the date in yyyy-mm-dd format for which the data is to be fetched. (required)
  pageToken: string, Token to specify next page.
  parameters: string, Represents the application name, parameter name pairs to fetch in csv as app_name1:param_name1, app_name2:param_name2.

Returns:
  An object of the form:

    { # JSON template for a collection of usage reports.
    "nextPageToken": "A String", # Token for retrieving the next page
    "kind": "admin#reports#usageReports", # Th

你可以通过(将"function"替换为你的函数名)获得参数的数量:

function.__code__.co_argcount ## 2

参数的名称为:

function.__code__.co_varnames ## ('a', 'b')

Inspect.getargspec()来满足您的需求

from inspect import getargspec

def func(a, b):
    pass
print len(getargspec(func).args)
someMethod.func_code.co_argcount

或者,如果当前函数名未确定:

import sys

sys._getframe().func_code.co_argcount

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。