我想把一个大的Python函数重构成更小的函数。例如,请考虑以下代码段:
x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
当然,这是一个微不足道的例子。实际上,代码更复杂。我的观点是,它包含许多必须传递给提取函数的局部范围变量,这些变量可能如下所示:
def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9):
x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
return x
问题是pylint会触发关于参数过多的警告。 我可以这样做来避免警告:
def mysum(d):
x1 = d['x1']
x2 = d['x2']
...
x9 = d['x9']
x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9
return x
def mybigfunction():
...
d = {}
d['x1'] = x1
...
d['x9'] = x9
x = mysum(d)
但这种方法对我来说很难看,它需要编写很多甚至是多余的代码。
有更好的办法吗?
您可以很容易地更改pylint中允许的最大参数数。只需打开pylintrc文件(如果还没有,则生成该文件)并更改:
最大参数=5
致:
最大参数=6#或任何适合您的值
从派林的manual
你想要一个更好的方法来传递参数,还是仅仅是一种方法来阻止
pylint
给你带来困难?如果是后者,我似乎记得您可以通过在代码中按以下行放置pylint
控制注释来停止唠叨:或:
记得尽快打开它们。
在我看来,传递大量的参数和解决方案,主张将它们全部打包到某个容器参数中,除了阻止
pylint
唠叨您之外,并不能真正解决任何问题,本身就没有什么问题。如果你需要传递20个参数,那么就传递它们。这可能是必需的,因为您的函数做得太多,重新分解可能会有帮助,这是您应该考虑的问题。但这不是我们真正能做的决定,除非我们看到真正的代码是什么。
首先,一个Perlis's epigrams:
10个论点中的一些大概是相关的。将它们组合成一个对象,然后传递给它。
举个例子,因为问题中没有足够的信息可以直接回答:
那么你的10参数函数:
变成:
呼叫方更改为:
相关问题 更多 >
编程相关推荐