我有九个非常相似的功能,它们的功能略有不同。它们都采用相同的输入,并在对它们执行类似的算术后返回相同类型的输出。作为一个非常简单的并行示例,考虑基本的数学计算:加法,减法,乘法,除法,模数等,所有这些都需要2个输入并产生一个输出。让我们说一些外力控制应用哪种操作,如下所示:
def add(a, b):
return a+b
def sub(a, b):
return a-b
def mul(a, b):
return a*b
....
# Emulating a very basic switch-case
cases = {'a' : add,
's' : sub,
'm' : mul,
'd' : div,
...
... }
# And the function call like so (`choice` is external and out of my control):
cases[choice](x, y)
有没有一种很好的方法将所有这些功能打包在一起(主要是为了避免为所有人编写类似的docstrings
:- P)?实际上,通常情况下是否有更好的方法来编写上述功能?
答案 0 :(得分:4)
取决于这些其他方法的大小,您可以在一个方法中将它们全部打包在一起,并在switch语句中使用lambda。
def foo(a, b, context):
""" Depending on context, perform arithmetic """
d = {
'a': lambda x, y: x + y,
's': lambda x, y: x - y,
..
}
return d[context](a, b)
foo(x, y, choice)
将所有内容放在一个方法中,避免使用多个文档字符串。