[英]Write a generator or return a generator?
Inside a container class, when I want to iterate over its items (or transformations of its items, or a subset of its items), I can either write a generator (like f
) or return a generator (like g
): 在容器类中,当我想迭代其项目(或其项目的变换或其项目的子集)时,我可以编写生成器(如f
)或返回生成器(如g
):
class SomeContainer:
def __init__(self):
self.data = [1, 'two', 3, 'four']
def f(self):
for e in self.data: yield e + e
def g(self):
return (e + e for e in self.data)
sc = SomeContainer()
for x in sc.f(): print(x)
for x in sc.g(): print(x)
I do not need to pass information into the generator via send
. 我不需要通过send
将信息传递给生成器。
Apparently both ways behave identical (at the surface). 显然两种方式都表现相同(在表面)。
Which approach is preferable and why? 哪种方法更可取,为什么?
Which approach creates less overhead or has other advantages I fail to spot? 哪种方法可以减少开销,或者具有其他我未能发现的优势?
Generator comprehensions (such as in g()
) would be slightly faster. 生成器理解(例如在g()
)会稍快一些。
Explicit loops (such as in f()
) would probably be more readable if your logic beccomes more complex than in the simple example you provided. 如果您的逻辑比您提供的简单示例更复杂,那么显式循环(例如在f()
)可能更具可读性。
Other than that, I can't think of any material differences. 除此之外,我想不出任何重大差异。
But remember what they say: 但请记住他们说的话:
Premature optimization is the root of all evil! 过早优化是万恶之源!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.