参见以下程序
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)
。但我使用它的代码不允许。所以我使用实例成员来传递数据。
答案 0 :(得分:2)
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
(我刚刚将cur_word = word
更改为self.cur_word = word
中的parse