问题描述
例如,我有一个返回排列列表的基本方法.
For example, I have a basic method that will return a list of permutations.
import itertools
def perms(elements, set_length=elements):
data=[]
for x in range(elements):
data.append(x+1)
return list(itertools.permutations(data, set_length))
现在我明白了,在当前状态下,这段代码不会运行,因为第二个 elements
没有定义,但是有没有一种优雅的方式来完成我在这里尝试做的事情?如果这还不清楚,我想让默认的 setLength
值等于传入的第一个参数.谢谢.
Now I understand, that in its current state this code won't run because the second elements
isn't defined, but is there and elegant way to accomplish what I'm trying to do here? If that's still not clear, I want to make the default setLength
value equal to the first argument passed in. Thanks.
推荐答案
否,函数关键字参数默认值是在定义函数时确定的,而不是在执行函数时确定.
No, function keyword parameter defaults are determined when the function is defined, not when the function is executed.
将默认设置为 None
并检测:
Set the default to None
and detect that:
def perms(elements, setLength=None):
if setLength is None:
setLength = elements
如果您需要能够将 None
指定为参数,请使用不同的标记值:
If you need to be able to specify None
as a argument, use a different sentinel value:
_sentinel = object()
def perms(elements, setLength=_sentinel):
if setLength is _sentinel:
setLength = elements
现在调用者可以将 setLength
设置为 None
并且它不会被视为默认值.
Now callers can set setLength
to None
and it won't be seen as the default.
这篇关于有没有办法将默认参数设置为等于另一个参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!