2013-02-01 102 views
0

請參見下面的程序實例成員數據不傳遞給實例方法

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

你需要在'parse'使用'self.cur_word',而不是'cur_word'。 – cha0site

+0

這意味着我無法創建SSCCE :( –

回答

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 = wordself.cur_word = wordparse

相關問題