[英]Python - find number of passed arguments inside a function
Imagine I want to define a function with all arguments having default values: 想象一下,我想用所有具有默认值的参数来定义一个函数:
def fun(a=2, b=1):
...
The logic inside the function is that: if nothing is passed, use the default value; 该函数内部的逻辑是:如果未传递任何内容,则使用默认值;否则,使用默认值。 if only a is passed, then b is always equal to a/2;
如果仅通过a,则b始终等于a / 2; if both a and b are passed, then use the passed values.
如果同时传递了a和b,则使用传递的值。
The problem in completing this function is that it seems difficult to tell the difference between (for example) fun(4) and fun(4,1) since I don't know whether the b=1 is provided outside or is just the default value. 完成此功能的问题在于,似乎很难分辨(例如) fun(4)和fun(4,1)之间的区别,因为我不知道b = 1是在外部提供还是默认提供的值。
One obvious way to get around is to use *args, however, in my case I want to keep the default values and names. 解决这个问题的一种明显方法是使用* args,但是在我的情况下,我想保留默认值和名称。 Therefore it seems the only way out is to know inside fun() how many arguments are passed when it's called.
因此,似乎唯一的出路是在fun()内部知道调用它时传递了多少个参数。 I guess there might be some system function to use, but I didn't succeed in finding them.
我猜可能会有一些系统功能要使用,但是我没有成功找到它们。 Any idea how could this work would be very helpful.
任何想法如何这项工作将是非常有益的。
Thanks! 谢谢! :)
:)
You can have (for instance) the default value of b
be None
, and then work out inside your function what value b
should take. 例如,您可以将
b
的默认值设置为None
,然后在函数内部计算b
值。
def fun(a=2, b=None):
if b is None:
b = a/2
...
This will give you: 这将为您提供:
f() : a=2, b=1
f(4) : a=4, b=2
f(4,1) : a=4, b=1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.