我想在每次调用 Generator 类时从文件中打印 n 行。
我尝试过以下方法:
class FileReader:
def __init__(self, file):
with open(file, 'r') as fin:
read_file = fin.read()
# gen-comp yielding stripped lines
lines = (line.strip() for line in read_file)
print(lines)
这只是返回所有行。
最佳答案
您可以实现一个 __call__
方法,例如,
import sys
from itertools import islice
class FileReader:
def __init__(self, fname, len=3):
self.fname = fname
self._len = len
def __enter__(self):
self.fd = open(self.fname, 'r')
return self
def __call__(self):
return list(islice(self.fd, self._len))
def __exit__(self, exc_type, exc_val, exc_tb):
if self.fd:
self.fd.close()
with FileReader(sys.argv[1]) as f:
print(f())
print(f())
关于python - 从 Python 中的 Generator 类生成 n 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58200007/