Hello I'm trying to make a class that represents an area that can be iterated with a for ... in loop. I know that it can be done with two for loops, but I'm trying to understand generators in general.
I'm using Python 3
I've written this but doesn't work:
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
Thanks you