How to iterate on the data attributes of an instance object, returning two values ​​at a time?


I need to return two values at a time, so I have:

class IterableObject(object):
  def __iter__(self):
    for item in self.__dict__:
      return  self.__dict__[item + 1], self.__dict__[item]

So I can have:

myObj1, myObj2 = IterableObject()

value = myObj1.balance - myObj2.balance

Of course it did not work. What am I doing wrong? I think I can not add value on item like that.

In the itertools documentation there is an example function called pairwise that you can copy into your project:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

Use it like:

for x1, x2 in pairwise(some_iterable):
    # etc..

Note that when you iterate over a dict the items are not necessarily returned in order, so you should sort first.