[英]Count the number of arguments actually passed to a python function
I would like to retrieve the number of arguments that have been passed to a Python function. In fact I am writting a Matlab code in Python and in Matlab, the code line is:我想检索已传递给 Python function 的 arguments 的编号。实际上我在 Python 和 Matlab 中编写了 Matlab 代码,代码行是:
if (nargin > 2)
...
end
I would like to do the same thing in Python with a function that have this form: def my_func(a,b,c=3,d=4, ...):
我想在 Python 中使用具有以下形式的 function 做同样的事情:
def my_func(a,b,c=3,d=4, ...):
When calling it, I would be able to retrieve the number of passed arguments, for instance:调用它时,我将能够检索通过的号码 arguments,例如:
my_func(1,2)
would return 2 my_func(1,2)
会返回 2
my_func(1,2,3)
would return 3 my_func(1,2,3)
会返回 3
my_func(1,2,3,4)
would return 4 etc. my_func(1,2,3,4)
会返回 4 等等。
I have seen some topics but only giving the number of arguments and description of the function, and not the number of arguments passed when calling it in a script.我看过一些主题,但只给出了 arguments 的编号和 function 的描述,而没有在脚本中调用它时传递的 arguments 的编号。
I hope that I am clear in explaining my issue.我希望我能清楚地解释我的问题。
Best regards, MOCHON Rémi最好的问候, MOCHON Rémi
Below code will work for you下面的代码将为您工作
def param_count(*args):
return len(args)
Not exactly what you ask for, but a simple way to achieve this is to count the number of args
and kwargs
using a decorator, and then pass it to the function.不完全是您要求的,但实现此目的的一种简单方法是使用装饰器计算
args
和kwargs
的数量,然后将其传递给 function。
The decorator will look like this:装饰器将如下所示:
def count_nargin(func):
def inner(*args, **kwargs):
nargin = len(args) + len(kwargs)
return func(*args, **kwargs, nargin=nargin)
return inner
You will then have to modify your function to accept the nargin
parameter:然后,您必须修改您的 function 以接受
nargin
参数:
@count_nargin
def my_func(a,b,c=3,d=4,nargin=None):
print(nargin)
For example, calling the above function returns:例如调用上面的 function 返回:
>>> my_func(1,2)
2
>>> my_func(1,2,3)
3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.