我正在寻找与此功能等效的面向对象:
def lazy_gen_func(path):
for line in open(path):
for token in line.split():
yield token
Related answers建议采用以下方法:
class eager_gen_obj(object):
def __init__(self, path):
f = open(path)
self.text = [token for line in f for token in line.split()]
self.index = 0
def __iter__(self):
return self
def __next__(self):
try:
result = self.text[self.index]
except IndexError:
raise StopIteration
self.index += 1
return result
缺点是在调用__init__时必须在内存中加载完整的源文件。
如何创建自定义生成器对象以延迟展平嵌套源数据?
答案 0 :(得分:1)
您可以从原始函数 - self._generator = lazy_gen_func(path)
- 或从等效的生成器表达式中包装生成器:
class LazyGenObj:
def __init__(self, path):
f = open(path)
self._generator = (token for line in f for token in line.split())
def __iter__(self):
return self
def __next__(self):
return next(self._generator)
将文件对象传递给它而不是路径也是一个好主意,这样调用者可以自由地明确地关闭它。