What is the advantage of using an generator(yield) inside an __iter__() function? After reading through Python Cookbook I understand "If you want a generator to expose extra state to the user, don’t forget that you can easily
implement it as a class, putting the generator function code in the __iter__() method."
import io
class playyield:
def __init__(self,fp):
self.completefp = fp
def __iter__(self):
for line in self.completefp:
if 'python' in line:
yield line
if __name__ =='__main__':
with io.open(r'K:\Data\somefile.txt','r') as fp:
playyieldobj = playyield(fp)
for i in playyieldobj:
print I
Questions:
- What does extra state means here?
- What is the advantage of using
yieldinside__iter__ ()instead of using a separate function foryield?