ube*_*kel 2 python yield generator
所以我想制作一个arff阅读器(类似于csv文件格式).
我想用它yield来创建一个迭代器,但也要为这个迭代器添加属性.
例如:
data = arff.reader(my_fname)
print data.relation
for row in data:
print row
Run Code Online (Sandbox Code Playgroud)
但在读者定义中:
def reader(fname):
reader.relation = fname # this is assigned to the function, not the generator
yield 1
yield 2
Run Code Online (Sandbox Code Playgroud)
有没有办法使用yield来做到这一点,还是我坚持使用迭代器api?
你可以把它变成一个类.
class Reader(object): # Assuming Python <= 2.7
def __init__(self, fname):
self.fname = fname
def __iter__(self):
yield 1
yield 2
r = Reader("some file")
print r.fname ## 'some file'
for line in r:
print line ## 1 then 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |