使用一个参数数组的长度作为同一个函数的另一个参数的默认值
这是我第一次在 SO 中提问,所以如果我不知何故做得不正确,请不要犹豫,编辑它或要求我修改它.
This is my first time asking a question in SO, so if I'm somehow not doing it properly don't hesitate to edit it or ask me to modify it.
我认为我的问题有点笼统,所以我很惊讶之前没有找到任何与此主题相关的问题.如果我错过了它并且这个问题是重复的,如果你能提供一个链接到已经回答的地方,我将不胜感激.
I think my question is kind of general, so I'm quite surprised for not having found any previous one related to this topic. If I missed it and this question is duplicated, I'll be very grateful if you could provide a link to where it was already answered.
想象一下,我需要用(至少)三个参数来实现一个函数:一个数组 a
、一个 start
索引和一个 end
索引.如果未提供,start
参数应指向数组的第一个位置(start = 0
),而end
参数应设置到最后一个位置 (end = len(a) - 1
).显然,定义:
Imagine I need to implement a function with (at least) three parameters: an array a
, a start
index and an end
index. If not provided, the start
parameter should refer to the first position of the array (start = 0
), while the end
parameter should be set to the last position (end = len(a) - 1
). Obviously, the definition:
def function(a, start = 0, end = (len(a) - 1)):
#do_something
pass
不起作用,导致异常(NameError: name 'a' is not defined
).有一些解决方法,例如使用end = -1
或end = None
,并有条件地将其分配给len(a) - 1
如果在函数体内需要:
does not work, leading to an exception (NameError: name 'a' is not defined
). There are some workarounds, such as using end = -1
or end = None
, and conditionally assign it to len(a) - 1
if needed inside the body of the function:
def function(a, start = 0, end = -1):
end = end if end != -1 else (len(a) -1)
#do_something
但我觉得应该有一种更pythonic"的方式来处理这种情况,不仅是数组的长度,还有默认值是另一个(非可选)参数的函数的任何参数.遇到这样的情况你会怎么处理?条件分配是最好的选择吗?
but I have the feeling that there should be a more "pythonic" way of dealing with such situations, not only with the length of an array but with any parameter whose default value is a function of another (non optional) parameter. How would you deal with a situation like that? Is the conditional assignment the best option?
谢谢!
基于@NPE 在 具有相关预设参数的函数,使用 -1
或(更好)None
作为标记值的替代方法是使用对象(命名对象?) 即使 None
是函数的有效值,也可以使用.例如:
Based on the answer provided by @NPE in Function with dependent preset arguments, an alternative to using -1
or (better) None
as sentinel values is using an object (a named object?) which can be used even if None
is a valid value of the function. For example:
default = object()
def function(a, start = 0, end = default):
if end is default: end = (len(a) - 1)
return start, end
允许这样的调用: function([1,2,3,4])
返回 (0, 3)
allows a call like: function([1,2,3,4])
which returns (0, 3)
我个人觉得这个解决方案非常方便,至少对于我自己的目的
I personally find this solution quite convenient, at least for my own purpose
如果我们使用 last
而不是 default
,也许代码更易读:
Maybe the code is even more readable if we use last
instead of default
:
last = object()
def function(a, start = 0, end = last):
if end is last: end = (len(a) - 1)
return start, end