使用大量参数编写函数/方法的 Pythonic 方式
想象一下:
def method(self, alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota, kappa):
pass
该行超过了 79 个字符,那么,Python 的多行方式是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以在括号(或方括号)内包含换行符,例如
(当然,要包含的空格数量取决于您)
但在这种情况下,您还可以考虑
和/或
取决于您如何使用参数(和您希望如何调用该函数)。
You can include line breaks within parentheses (or brackets), e.g.
(the amount of whitespace to include is, of course, up to you)
But in this case, you could also consider
and/or
depending on how you use the arguments (and how you want the function to be called).
我认为回答这个问题的“Pythonic”方式是比语法更深入。向方法传递如此多的参数表明您的对象模型可能存在问题。
首先,您真的需要向此方法传递那么多参数吗?也许这表明这项工作可以在其他地方更好地完成(通过已经有权访问变量的对象)?
如果这确实是该方法的最佳位置,那么其中一些参数是否可以作为该对象本身的实例变量提供(通过
self
)?如果没有,你能重新定义父对象的职责来包含它们吗?
如果没有,您能否将任何单个参数封装在一个复合对象中,以形式化它们之间的关系?如果任何参数有任何共同点,那么这应该是可能的。
I think the 'Pythonic' way of answering this is to look deeper than syntax. Passing in that many arguments to a method indicates a likely problem with your object model.
First of all, do you really need to pass that many arguments to this method? Perhaps this is an indication that the work could be better done elsewhere (by an object that already has access to the variables)?
If this really is the best place for the method, then could some of those arguments be supplied as instance variables of this object itself (via
self
)?If not, can you redefine the responsibilities of the parent object to include them?
If not, can you encapsulate any of the individual arguments in a composite object that formalizes the relationship between them? If any of the arguments have anything in common, then this should be possible.
我将后续行缩进 2 级:
I indent the subsequent lines 2 levels:
我会这样写,
我认为它看起来漂亮又干净
I would write it like that
I think it looks nice and clean
另一种选择是在字典中传递参数。
Another option would be to pass the parameters in a dict.
一旦击中 79,我就分成左括号,如下所示:
当名称太长而无法放在左括号后面时,我会这样做:
I just split to the open bracket once 79 is hit, like this:
And when names are too long to be put after the opening bracket, I do it like this:
如果您有一个接受如此多变量作为参数的函数,那么您最不需要担心的就是缩进
If you have a function that takes so many variables as arguments, the last thing you have to worry about is indentation
为了便于阅读,当我有很长的名字时,我这样做:
For readability when I have long names I do this:
我通常这样做,我不知道这是否是最好的,但它确实有效。因为我必须分割线,所以我让它们同样长(如果可以的话):
另外,拥有如此数量的参数,我会建议与 David 相同,使用
*args
I usually do this, I don't know if it's the best, but it works. Since I have to split the line I make them equally longer (if I can):
Also, having such quantity of parameters I would recommend the same as David, use
*args