我如何才能找到一个Python函数的参数的数量?我需要知道它有多少普通参数和多少命名参数。
例子:
def someMethod(self, arg1, kwarg1=None):
pass
这个方法有2个参数和1个命名参数。
我如何才能找到一个Python函数的参数的数量?我需要知道它有多少普通参数和多少命名参数。
例子:
def someMethod(self, arg1, kwarg1=None):
pass
这个方法有2个参数和1个命名参数。
当前回答
对于那些想要在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:使用签名,因为getargespec()和getfulllargspec()已弃用。
然而,从Python 3.6开始(根据流行需求?),事情已经朝着更好的方向变化:
从Python 3文档页:
inspect.getfullargspec(函数) 在3.6版更改:此方法以前在Python 3.5中被记录为不赞成signature(),但为了恢复从遗留的getargspec() API迁移的单源Python 2/3代码明确支持的标准接口,该决定已被撤销。
其他回答
import inspect
inspect.getargspec(someMethod)
查看inspect模块
对于那些想要在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:使用签名,因为getargespec()和getfulllargspec()已弃用。
然而,从Python 3.6开始(根据流行需求?),事情已经朝着更好的方向变化:
从Python 3文档页:
inspect.getfullargspec(函数) 在3.6版更改:此方法以前在Python 3.5中被记录为不赞成signature(),但为了恢复从遗留的getargspec() API迁移的单源Python 2/3代码明确支持的标准接口,该决定已被撤销。
Dimitris Fasarakis Hilliard的公认答案建议以字符串格式获取参数,但我认为在解析这个字符串时可能会犯错误,因此我直接使用inspect模块创建了一个参数列表
import inspect
def my_function(a,b,c):
#some code
pass
result=list(inspect.signature(my_function).parameters.keys())
print(result)
['a','b','c']
除此之外,我还看到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
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。通过检查获得全部规格。在上面的代码中获取目标规格。