所以我想创建一个函数,生成从'start'到'end'的连续数字,与'size'一样多。对于迭代,它将在函数内部计算。但我有问题设置参数'end'的默认值。在我进一步解释之前,下面是代码:
# Look at this -------------------------------
# ||
# /
def consecutive_generator(size=20, start=0, end=(size+start)):
i = start
iteration = (end-start)/size
arr = []
temp_size = 0
while temp_size < size:
arr.append(i)
i += iteration
temp_size += 1
return arr
# with default end, so the 'end' parameter will be 11
c1= consecutive_generator(10, start=1)
print(c1)
# with end set
c2= consecutive_generator(10, end=20)
print(c2)
如上所示(在'end'参数的默认值上),我想要实现的是'end'参数,其默认值为'start' + 'size'参数(然后迭代将为1)
输出肯定是错误的。那么我该怎么做呢?(这是我第一次问stackoverflow对不起,如果我犯了一个错误)
(关闭)
这是一个非常标准的模式:
def consecutive_generator(size=20, start=0, end=None):
if end is None:
end = size + start
默认的方法是Samwise所说的,但是有一个替代的解决方案可能同样有效。
def consecutive_generator(size=20, start=0, **kwargs):
end = kwargs.get('end', size+start)
此方法允许您获取end(如果它存在),或者简单地设置end(如果它不存在)的值。
要调用它,如果您想将其设置为默认值以外的其他值,则此方法确实要求函数调用具有指定的参数end
。
consecutive_generator(20, 0, end=50)
dict.get
也许可以考虑查看一下range和numpy.linspace
的文档根据Python的文档,
默认形参值在函数定义执行时从左到右求值
因此参数的默认值不能从函数调用时传递的其他动态值中求值。
您应该使用可区分的值,如None
作为默认值。然后,您可以检查它并动态计算适当的默认值。例如,
def consecutive_generator(size=20, start=0, end=None):
if end is None:
end = size + start
...
如果您需要None
作为调用者传递的有效值,您可以使用其他对象或其他东西来区分有效值。
default_end = object()
def consecutive_generator(size=20, start=0, end=default_end):
if end is default_end:
end = size + start
...