实例成员数据不会传递给实例方法



请参阅以下程序

class MyIterator:
    cur_word = ''
    def parse(self):
        data = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
        for index in range(1,3):
            (word, num) = data[index]
            cur_word = word
            yield self.unique_str(num)
    def unique_str(self, num):
        data = ['a', 'b']
        for d in data:
            yield "%s-%d-%s" % (self.cur_word, num, d)

miter = MyIterator()
parse = miter.parse()
for ustrs in parse:
    for ustr in ustrs:
        print ustr

此代码的输出为

-2-a
-2-b
-3-a
-3-b

但我希望它是

two-2-a
two-2-b
three-3-a
three-3-b

是的,我知道我可以跑yield self.unique_str(word, num).但是我使用的代码是不允许的。所以我使用实例成员来传递数据。

>MyIterator.parse不会更改实例的当前单词。

这有效:

class MyIterator:
    cur_word = ''
    def parse(self):
        data = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
        for index in range(1,3):
            (word, num) = data[index]
            self.cur_word = word
            yield self.unique_str(num)
    def unique_str(self, num):
        data = ['a', 'b']
        for d in data:
            yield "%s-%d-%s" % (self.cur_word, num, d)

miter = MyIterator()
parse = miter.parse()
for ustrs in parse:
    for ustr in ustrs:
        print ustr

(我刚刚在parse中将cur_word = word更改为self.cur_word = word

最新更新