方法链接——多少个链接方法就足够了?
是否有关于何时停止链接方法并将链分解为多个表达式的指导原则?
考虑一下这个 Python 代码,它构建了一个字典,以单词作为键,相应的计数作为值:
def build_dict(filename):
with open(filename, 'r') as f:
dict = defaultdict(int)
for word in f.read().lower().split(): # too much?
dict[word] += 1
return dict
链接 3 个方法可以吗?通过拆分表达式我会获得任何明显的好处吗?
Are there any guidelines on when to stop chaining methods and instead break up the chain into several expressions?
Consider e.g. this Python code, which build up a dictionary, with word as key and the corresponding count as the value:
def build_dict(filename):
with open(filename, 'r') as f:
dict = defaultdict(int)
for word in f.read().lower().split(): # too much?
dict[word] += 1
return dict
Is chaining 3 methods okay? Would I gain any noticable benefit by split the expression up?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅链接两个有什么意义? 如果您进行方法链接,请正确执行。
这更多是一个格式问题,如果单行太多,我更喜欢
另一个问题是调试器,如果您想跟踪
Bar<,它会强制您跟踪
Foo
/代码>。What would be the point of chaining only two? If you do method chaining, do it right.
It's more an issue of formatting, if it gets to much for a single line, I prefer
Another issue can be debuggers, that force you to trace into
Foo
if you want to trace intoBar
.不使用长链的原因之一是它会掩盖回溯错误消息。
当长链中的任何位置引发异常时,回溯错误消息仅告诉您发生异常的行,而不是链的哪一部分。
如果您确信不会发生异常,那么
可能会更好,
因为内存被字符串
contents
和列表words
消耗,并且直到此代码块才被释放结束(假设没有对同一对象进行其他引用)。因此,如果内存紧张,您可能需要考虑链接。如果内存不是问题,特别是如果
words
或contents
可以在代码中稍后再次使用,那么分配一个变量来引用它们当然会更快,因为read
、lower
和/或split
方法不必再次调用。One reason not to use long chains is that it obscures traceback error messages.
When an exception is raised anywhere in the long chain, the traceback error message only tells you the line on which the Exception occurred, not which part of the chain.
If you are confident that no exception will occur, then
might be preferable to
because memory is consumed by the string
contents
and the listwords
and is not released until this block of code ends (assuming no other references are made to the same objects). So if memory is tight, you might want to consider chaining.If memory is not a problem, and particularly if
words
orcontents
could be used again later in the code, then assigning a variable to reference them will of course be faster since theread
,lower
and/orsplit
methods won't have to be called again.这很大程度上取决于个人喜好,但如果 f 中的文本不会在其他地方使用,那也没关系。当链太长时,普通读者会不清楚链实际返回的内容。将其拆分的唯一好处是您可以使用中间结果并且您可能会获得清晰度。
This is largely a matter of personal preference, but if the text in f isn't going to be used elsewhere then that's fine. The point at which it becomes unclear to a casual reader what the chain actually returns is the point at which it's too long. The only benefits to splitting it up are that you can use intermediate results and you may gain clarity.