Carlos Gant Carlos Gant - 1 year ago 79
Python Question

How make an area iterable by each point in python

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

Answer Source

here is a simple example how it works:

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

I hope this helps. I don't understand what you want to do with your class. There is a good tutorial here.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download