See the following program
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
Output of this code is
-2-a
-2-b
-3-a
-3-b
But I want it to be
two-2-a
two-2-b
three-3-a
three-3-b
Yes I know I can run yield self.unique_str(word, num). But the code I am using its not allowed. So I used an instance member to pass the data.
MyIterator.parsedoesn’t change the instance’s current word.This works:
(I just changed
cur_word = wordtoself.cur_word = wordinparse)