处理未使用函数参数的最佳方式



假设用户给了我一个列表,其中包含可变数量的函数,这些函数具有固定数量的参数a, b和c。所有函数都具有固定类型。有时会用到所有的参数,但有时不会。例如:

def two_list_sum_mult(a: List, b: List, c: int):
""" Sums the elements on each list and multiplies it by a constant.
"""
return c * (sum(a) + sum(b))
def list_sum_mult(a: List, b: List, c: int):
""" Sums the elements on list a and multiplies it by a constant.
"""
return c * sum(a)
def list_sum_reciprocals(a: List, b: List, c: int):
""" Returns the sum of the reciprocals of each element of the list a.
"""
return sum([1/x for x in a])

用户传递一个函数列表,以及函数的参数。然后,我的函数循环遍历所有的函数,计算结果,然后用这个结果计算一些东西。例如:

def function_sum(functions: List, a: List, b: List, c: int):
""" Computes all the functions and adds the results.
"""
total = 0
for f in functions:
total += f(a, b, c)

return total

在不使用函数的实参时,处理它们的最佳方法是什么?换句话说:是否可以为函数提供未使用的参数,或者是否有更好的方法来完成所有这些?

保留未使用的参数是可以的,但是这可能会产生误导,并且一些编程人员会抱怨。

另一种可以使变量不被使用的方法是使用_作为变量名或在变量名前加上_。例如:

def two_list_sum_mult(a: List, b: List, c: int):
""" Sums the elements on each list and multiplies it by a constant.
"""
return c * (sum(a) + sum(b))
# replace `b` with `_` or `_b`
def list_sum_mult(a: List, _, c: int):
""" Sums the elements on list a and multiplies it by a constant.
"""
return c * sum(a)
# as you only care about the first argument you can ignore the others with `*_`
def list_sum_reciprocals(a: List, *_):
""" Returns the sum of the reciprocals of each element of the list a.
"""
return sum([1/x for x in a])

可以使用未使用的参数,这些参数可以有一个默认值

最新更新