chuiii chuiii - 14 days ago 5
Python Question

How to override __iter__() for custom class?

What I'm trying to do is reuse generator

class Rect(object):
...
def __iter__(self):
for y in xrange(self.tl.y, self.br.y + 1):
for x in xrange(self.tl.x, self.br.x + 1):
yield Point(x, y)


in child class. I've tried write something like

class Block(Rect):
...
def __iter__(self):
for p in super(Block, self):
yield p + self.offset


but obviously that didn't work.

My question is can that be done without copying code from parent class and what is most pythonic approach to re-usability of inherited code.

Answer

You can do it as follows:

class Block(Rect):
    def __iter__(self):
        for p in super(Block, self).__iter__():
            yield p + self.offset