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
感謝您
我試過你的代碼,它的工作原理和希望的一樣。什麼「不起作用」? –
嘗試使用兩個'for'循環迭代點,不涉及'Area'類。這可能會讓你更明白你做錯了什麼。 – user2357112
切換for循環。 –