Python如何设置依赖其他参数取值的函数形参默认值
错误原因
Python 函数的参数默认值仅在函数定义阶段计算一次,无法依赖其他入参的动态值——函数定义时size和start还没有绑定调用时传入的实际数值,直接写end=(size+start)会直接抛出未定义变量的错误。
实现方案
将end的默认值设为None作为占位符,在函数内部逻辑开头再判断:如果用户没有传入end参数,就计算end = start + size即可。调用时如果要跳过前面的默认参数传后面的参数,保持使用关键字参数传参的习惯即可,和你现有调用逻辑完全兼容。
修正后完整代码
def consecutive_generator(size=20, start=0, end=None): # 处理end默认值逻辑 if end is None: end = start + size i = start iteration = (end - start) / size arr = [] temp_size = 0 while temp_size < size: arr.append(i) i += iteration temp_size += 1 return arr # 用默认end,此时end=1+10=11,步长为1 c1 = consecutive_generator(10, start=1) print(c1) # 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 手动设置end=20,步长为(20-0)/10=2 c2 = consecutive_generator(10, end=20) print(c2) # 输出:[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
可选边界优化
如果存在start == end的场景,可提前判断避免除以0的错误,比如在计算步长前加判断:
if start == end: return [start] * size
内容的提问来源于stack exchange,提问作者Yusuf Syam
相关产品推荐
相关产品推荐

