Paddy wrote: > Pierre Thibault wrote: > > Hello! > > > > I am currently trying to port a C++ code to python, and I think I am stuck > > because of the very different behavior of STL iterators vs python > > iterators. What I need to do is a simple arithmetic operations on objects > > I don't know. In C++, the method doing that was a template, and all that > > was required is that the template class has an iterator conforming to the > > STL forward iterator definition. Then, the class would look like: > > > <SNIP> > > Then I discovered python and wanted to use all its goodies. I thought it > > would be easy to do the same thing but I can't: the iterator mechanism is > > read-only, right? So it does no make sense to write: > > > > io1 = iter(object1) > > io2 = iter(object2) > > > > try: > > while 1: > > io1.next() += io2.next() > > except StopIteration: > > pass > > > > That won't work: > > SyntaxError: can't assign to function call > > > > Here is my question: how could I do that and retain enough generallity? > > > > Thanks! > > > > Pierre > > Pierre, > You should be able to write > io1.next().param += io2.next().param > If iter(object1) and iter(object2) both return classes or instances > with the appropriate parameter. > Here is what I was thinking of: > > > class ParamHolder(object): > def __init__(self, n): > self.param = n > > class C1(object): > def __init__(self,m): > self.value = [ParamHolder(n) for n in range(m)] > def __getitem__(self, p): > return self.value[p] > > obj1 = C1(5) > obj2 = C1(5) > > io1 = iter(obj1) > io2 = iter(obj2) > > print "obj1 pre loop",[r.param for r in obj1.value] > > try: > while 1: > io1.next().param += io2.next().param > except StopIteration: > pass > > print "obj1 post loop",[r.param for r in obj1.value] > > - Paddy.
I don't like the try/except code and would write something like the following: >>> obj1 = C1(5) >>> obj2 = C1(5) >>> from itertools import izip >>> for x,y in izip(obj1, obj2): ... x.param += y.param ... >>> print "obj1 post for loop",[r.param for r in obj1.value] obj1 post for loop [0, 2, 4, 6, 8] >>> - Paddy. -- http://mail.python.org/mailman/listinfo/python-list