我想将一个大的 Python 函数重构为更小的函数.例如,请考虑以下代码片段:
I want to refactor a big Python function into smaller ones. For example, consider this following code snippet:
x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9当然,这是一个微不足道的例子.在实践中,代码更复杂.我的观点是它包含许多必须传递给提取函数的局部范围变量,它们可能如下所示:
Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to be passed to the extracted function, which could look like:
def mysum(x1, x2, x3, x4, x5, x6, x7, x8, x9): x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 return x问题是 pylint 会触发关于参数过多的警告.我可以通过执行以下操作来避免警告:
The problem is that pylint would trigger a warning about too many arguments. I could avoid the warning by doing something like:
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)但是这种方法对我来说很丑陋,它需要编写大量甚至是多余的代码.
but this approach loos ugly to me, it requires writing a lot of code that is even redundant.
有更好的方法吗?
推荐答案第一个,玻璃市的警句:
"如果您有一个包含 10 个参数,你可能错过了一些."
"If you have a procedure with 10 parameters, you probably missed some."
这 10 个参数中的一些可能是相关的.将它们组合成一个对象,然后将其传递.
Some of the 10 arguments are presumably related. Group them into an object, and pass that instead.
举个例子,因为问题中没有足够的信息来直接回答:
Making an example up, because there's not enough information in the question to answer directly:
class PersonInfo(object): def __init__(self, name, age, iq): self.name = name self.age = age self.iq = iq然后是你的 10 个参数函数:
Then your 10 argument function:
def f(x1, x2, name, x3, iq, x4, age, x5, x6, x7): ...变成:
def f(personinfo, x1, x2, x3, x4, x5, x6, x7): ...并且调用者更改为:
personinfo = PersonInfo(name, age, iq) result = f(personinfo, x1, x2, x3, x4, x5, x6, x7)更多推荐
Python:避免关于参数过多的 pylint 警告
发布评论