6

我可以向 Python 生成器添加成员变量/方法吗?

我想要以下几行的东西,这样我就可以“偷看”成员变量 j:

def foo():
    for i in range(10):
        self.j = 10 - i
        yield i

gen = foo()
for k in gen:
    print gen.j
    print k

是的,我知道我每次都可以返回 i AND j。但我不想那样做。我想看看生成器中的一个本地。

4

2 回答 2

9

您可以创建一个对象并操作__iter__接口:

class Foo(object):
    def __init__(self):
        self.j = None
    def __iter__(self):
        for i in range(10):
            self.j = 10 - i
            yield i

my_generator = Foo()

for k in my_generator:
    print 'j is',my_generator.j
    print 'k is',k

印刷:

j is 10
k is 0
j is 9
k is 1
j is 8
k is 2
j is 7
k is 3
j is 6
k is 4
j is 5
k is 5
j is 4
k is 6
j is 3
k is 7
j is 2
k is 8
j is 1
k is 9
于 2009-12-21T20:21:10.980 回答
2

我认为这很丑陋,但它应该做你想做的事。不过,我宁愿每次都返回 i AND j :-)

class Foo(object):
    def foo(self):
        for i in range(10):
            self.j = 10 - i
            yield i

genKlass = Foo()
gen = genKlass.foo()
for k in gen:
    print genKlass.j
    print k
于 2009-12-21T20:20:51.257 回答