【问题标题】:Is there a way to add/modify attributes of generators that were created with yield?有没有办法添加/修改使用 yield 创建的生成器的属性?
【发布时间】:2011-12-01 14:55:03
【问题描述】:

所以我想做一个arff reader(类似于csv文件格式)。

我想使用yield 来创建一个迭代器,同时也想给这个迭代器添加属性。

例如:

data = arff.reader(my_fname)
print data.relation
for row in data:
    print row

但在读者定义中:

def reader(fname):
    reader.relation = fname # this is assigned to the function, not the generator
    yield 1
    yield 2

有没有办法使用 yield 来做到这一点,还是我坚持使用迭代器 api?

【问题讨论】:

    标签: python generator yield


    【解决方案1】:

    你可以把它变成一个类。

    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
    

    【讨论】:

    • 如果您调用方法__iter__ 而不是read,您可以只使用for line in r: 来遍历类。
    • @Duncan 是正确的。这就是我所说的“坚持使用迭代器 api”的意思。
    • @Duncan:哈,我忘了。固定的。我想你是,ubershmekel。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    相关资源
    最近更新 更多