我如何才能找到一个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

其他回答

除此之外,我还看到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
import inspect
inspect.getargspec(someMethod)

查看inspect模块

这是获取函数的强制参数数量的解决方案(*)

如果使用了一些不常见的参数规范(具有默认值的仅限位置参数,没有默认值的仅限关键字参数,等等),那么本文提出的许多解决方案都无法实现这一目的。

from typing import Callable, Any
import inspect

def get_mandatory_argcount(f: Callable[..., Any]) -> int:
    """Get the number of mandatory arguments of a function."""
    sig = inspect.signature(f)
    
    def parameter_is_mandatory(p: inspect.Parameter) -> bool:
        return p.default is inspect.Parameter.empty and p.kind not in (
            inspect.Parameter.VAR_POSITIONAL,
            inspect.Parameter.VAR_KEYWORD,
        )
    
    return sum(parameter_is_mandatory(p) for p in sig.parameters.values())

# mandatory keyword-only
def f1(b=2, *args, c, d=1, **kwds): pass
print(get_mandatory_argcount(f1))

# positional only with default
def f2(a=1, /, b=3, *args, **kwargs): pass
print(get_mandatory_argcount(f2))

(*)我想把这个作为一个答案,以编程方式确定一个函数所需的参数数量- Python代替,但由于某种原因,这个问题被标记为重复的这个问题,尽管它专门询问所需参数的数量,而这个问题只询问参数的一般数量。

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。通过检查获得全部规格。在上面的代码中获取目标规格。

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

如果输入是类方法(因此包括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