2016-11-20 29 views
0

您好我正在嘗試創建一個類,該類代表可以用for ... in循環迭代的區域。我知道它可以用兩個for循環完成,但我試圖理解一般的生成器。如何使python中的每個點都可迭代區域

我使用Python的

我已經寫了這一點,但不起作用:

class Area: 
    def __init__(self, width, height): 
     self.width = width 
     self.height = height 

    def __iter__(self): 
     # my best try, clearly I don't understand 
     # something about generators 
     for x in range(0, self.width): 
      for y in range(0, self.height): 
       yield x, y 

area = Area(2, 3) 
for x, y in area: 
    print("x: {}, y: {}".format(x, y)) 

# I want this to output something like: 
# x: 0, y: 0 
# x: 1, y: 0 
# x: 0, y: 1 
# x: 1, y: 1 
# x: 0, y: 2 
# x: 1, y: 2 

感謝您

+2

我試過你的代碼,它的工作原理和希望的一樣。什麼「不起作用」? –

+0

嘗試使用兩個'for'循環迭代點,不涉及'Area'類。這可能會讓你更明白你做錯了什麼。 – user2357112

+1

切換for循環。 –

回答

1

這裏是一個簡單的例子,它是如何工作的:

class Fib: 
    def __init__(self, max): 
     self.max = max 

    def __iter__(self): 
     // The variables you need for the iteration, to store your 
     // values 
     self.a = 0 
     self.b = 1 
     return self 

    def __next__(self): 
     fib = self.a 
     if fib > self.max: 
      raise StopIteration // This is no error. It means, that 
           // The iteration stops here. 
     self.a, self.b = self.b, self.a + self.b 
     return fib 

我希望這可以幫助。我不明白你想要和你的班級做什麼。 有一個很好的教程here

邁克爾

相關問題