Using iterators to write in the structure being iterated through?
Paddy
paddy3118 at netscape.net
Wed Jul 26 18:55:23 EDT 2006
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.
More information about the Python-list
mailing list