6

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.

1
  • 2
    Perhaps it's a better idea to move Rect.__iter__'s implementation to a function (_iter_as_rect?) you can explicitly reuse. Commented Nov 25, 2016 at 10:46

1 Answer 1

6

You can do it as follows:

class Block(Rect):
    def __iter__(self):
        for p in super(Block, self).__iter__():
            yield p + self.offset
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.