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

例子:

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

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


当前回答

假设您可能正在处理基于类的方法或简单的函数,您可以像下面这样做。

如果输入是类方法(因此包括self),这将自动减去一个输入。

import types
def get_arg_count(fn):
    extra_method_input_count=1 if isinstance(fn, types.MethodType) else 0
    return fn.__code__.co_argcount-extra_method_input_count

然后你可以根据需要应用到函数或方法:

def fn1(a, b, c):
    return None

class cl1:
    def fn2(self, a, b, c):
        return None

print(get_arg_count(fn1)) #=> 3
print(get_arg_count(cl1().fn2)) #=> 3

其他回答

func.__code__。co_argcount给出了在*args之前任何参数的个数

函数。__kwdefaults__给你一个字典的关键字参数AFTER *args

func.__code__。Co_kwonlyargcount等于len(funct .__kwdefaults__)

函数。__defaults__提供了出现在*args之前的可选参数值

这里有一个简单的例子:

>>> def a(b, c, d, e, f=1, g=3, h=None, *i, j=2, k=3, **L):
    pass

>>> a.__code__.co_argcount
7
>>> a.__defaults__
(1, 3, None)
>>> len(a.__defaults__)
3
>>> 
>>> 
>>> a.__kwdefaults__
{'j': 2, 'k': 3}
>>> len(a.__kwdefaults__)
2
>>> a.__code__.co_kwonlyargcount
2

假设您可能正在处理基于类的方法或简单的函数,您可以像下面这样做。

如果输入是类方法(因此包括self),这将自动减去一个输入。

import types
def get_arg_count(fn):
    extra_method_input_count=1 if isinstance(fn, types.MethodType) else 0
    return fn.__code__.co_argcount-extra_method_input_count

然后你可以根据需要应用到函数或方法:

def fn1(a, b, c):
    return None

class cl1:
    def fn2(self, a, b, c):
        return None

print(get_arg_count(fn1)) #=> 3
print(get_arg_count(cl1().fn2)) #=> 3

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

from inspect import getargspec

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

除此之外,我还看到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
someMethod.func_code.co_argcount

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

import sys

sys._getframe().func_code.co_argcount