如何找到Python函数的参数个数?

Geo*_*lly 138 python function

如何找到Python函数的参数个数?我需要知道它有多少正常参数以及有多少命名参数.

例:

def someMethod(self, arg1, kwarg1=None):
    pass
Run Code Online (Sandbox Code Playgroud)

此方法有2个参数和1个命名参数.

Joc*_*zel 116

import inspect
inspect.getargspec(someMethod)
Run Code Online (Sandbox Code Playgroud)

参见检查模块

  • 通常你想要什么,但这不适用于内置函数.知道为内置函数获取此信息的唯一方法是解析它们的__doc__字符串,这很难但是可行. (5认同)
  • 这在Python 3中已弃用:https://docs.python.org/3/library/inspect.html#inspect.getargspec (4认同)

Jim*_*ard 96

以前接受的答案已经被弃用作为Python 3.0.inspect.getargspec现在应该选择Signature取代它的类,而不是使用你.

通过以下signature功能可以轻松地为函数创建签名:

from inspect import signature

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

sig = signature(someMethod)
Run Code Online (Sandbox Code Playgroud)

现在,您可以通过它快速查看其参数str:

str(sig)  # returns: '(self, arg1, kwarg1=None)'
Run Code Online (Sandbox Code Playgroud)

或者您也可以通过获取属性名称到参数对象的映射sig.parameters.

params = sig.parameters 
print(params['kwarg1']) # prints: kwarg1=20
Run Code Online (Sandbox Code Playgroud)

此外,你可以叫lensig.parameters也看到的参数此功能,需要数量:

print(len(params))  # 3
Run Code Online (Sandbox Code Playgroud)

params映射中的每个条目实际上都是一个具有更多属性的Parameter对象,使您的生活更轻松.例如,现在可以使用以下方法轻松执行抓取参数并查看其默认值:

kwarg1 = params['kwarg1']
kwarg1.default # returns: None
Run Code Online (Sandbox Code Playgroud)

类似地,包含在其中的其他对象parameters.


至于Python 2.x用户,虽然inspect.getargspec 被弃用,但语言将很快:-).该Signature课程不在该2.x系列中,也不会.所以你仍然需要合作inspect.getargspec.

至于Python 2和3之间的转换,如果你有一些代码依赖的接口getargspec在Python 2切换到signature3是太难了,你必须将有价值的选择使用inspect.getfullargspec.它提供了一个类似的接口getargspec(一个可调用的参数),以便获取函数的参数,同时还处理一些getargspec不具有的其他情况:

from inspect import getfullargspec

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

args = getfullargspec(someMethod)
Run Code Online (Sandbox Code Playgroud)

与此一样getargspec,getfullargspec返回NamedTuple包含参数的a.

print(args)
FullArgSpec(args=['self', 'arg1', 'kwarg1'], varargs=None, varkw=None, defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={})
Run Code Online (Sandbox Code Playgroud)

  • 不客气@GeorgSchölly。我很惊讶像这样的一个流行问题所提供的解决方案要么已被弃用,要么非常狡猾(在“co_argcount”属性中查看。) (3认同)
  • `getargspec` 不适用于内置函数:`getargspec(open)` 给出 `TypeError: <built-in function open> is not a Python function` 请参阅[此答案](http://stackoverflow.com/questions) /3276635/how-to-get-the-number-of-args-of-a-built-in-function-in-python) 一些想法... (3认同)
  • Python 2.x 中未实现 getfullargspec,您需要使用 getargspec (2认同)

小智 28

someMethod.func_code.co_argcount
Run Code Online (Sandbox Code Playgroud)

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

import sys

sys._getframe().func_code.co_argcount
Run Code Online (Sandbox Code Playgroud)

  • @noisecapella不需要第三方模块,当你可以简单地做`some_method .__ code __.co_argcount` (6认同)
  • @elyase,只需:`dir(someMethod)` - >`'func_code'`; 更进一步:`dir(someMethod.func_code)` - >`'co_argcount'.; 您可以使用内置的`dir()`来确定对象的可用方法. (4认同)

gim*_*mel 16

inspect.getargspec()

获取函数参数的名称和默认值.返回四个元组的元组:(args,varargs,varkw,defaults).args是参数名称的列表(它可能包含嵌套列表).varargs和varkw是*和**参数的名称或None.defaults是默认参数值的元组,如果没有默认参数,则为None; 如果这个元组有n个元素,它们对应于args中列出的最后n个元素.

在2.6版中更改:返回命名元组ArgSpec(args,varargs,keywords,defaults).

请参阅can-you-list-the-keyword-arguments-a-python-function-receive.


Khu*_*Ran 9

func.__code__.co_argcount给你之前任何参数的数量 *args

func.__kwdefaults__给你一个关键字参数 的字典AFTER *args

func.__code__.co_kwonlyargcount 等于 len(func.__kwdefaults__)

func.__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
Run Code Online (Sandbox Code Playgroud)


Gwa*_*Kim 6

您可以通过以下方式获取参数数量(将“function”替换为您的函数名称):

function.__code__.co_argcount ## 2

Run Code Online (Sandbox Code Playgroud)

以及参数的名称:

function.__code__.co_varnames ## ('a', 'b')
Run Code Online (Sandbox Code Playgroud)


Ven*_*thy 5

除此之外,我还看到大多数时候help()函数确实可以帮助您

例如,它提供了有关所采用参数的所有详细信息。

help(<method>)
Run Code Online (Sandbox Code Playgroud)

给出以下

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
Run Code Online (Sandbox Code Playgroud)

  • help函数仅显示文档字符串所说的内容。您甚至测试过它是否与问题中的函数定义兼容? (2认同)

HAl*_*tos 5

对于想要在 Python 2 和 Python 3.6+ 之间以可移植方式执行此操作的人来说,这是个好消息:使用inspect.getfullargspec()方法。它适用于 Python 2.x 和 3.6+

正如 Jim Fasarakis Hilliard 和其他人所指出的,它曾经是这样的:
1. 在 Python 2.x 中:使用inspect.getargspec()
2. 在 Python 3.x 中:使用签名,因为getargspec()getfullargspec()已被弃用。

然而,从 Python 3.6 开始(根据大众需求?),事情变得更好了:

从 Python 3文档页面

检查.getfullargspec(函数)

在 3.6 版中更改:此方法之前被记录为signature()在 Python 3.5 中被弃用,但该决定已被撤销,以便为从旧getargspec()API迁移的单源 Python 2/3 代码恢复明确支持的标准接口。