new.instancemethod __iter__

Christian Heimes lists at cheimes.de
Sat Feb 6 18:54:44 EST 2010


Martin Drautzburg wrote:
> The first case does what I expected, i.e. it iterates over whatever f()
> yields. In the second case nothing is printed. I have the impression
> that it still calls the original __iter__() method (the one defined at
> the class level).
>
> Why is that so?
> How can I replace the __iter__() method so it does what I want.

Virtually all __magic__ methods are looked up on the type, not the
instance. So obj.__iter__() translates into type(obj).__iter__(obj).

If you *really* need to overwrite __iter__ on your instance rather than
defining it on your class, you need to proxy the method call:

class MyObject(object):
   def __iter__(self):
      return self.myiter()

obj = MyObject()
obj.myiter = myiter

That should do the trick.

Christian



More information about the Python-list mailing list