7

I'm not sure, whether it's an easy problem with easy solution or it's something that needs to dig a little deeper.

Let's say I have an object Item with variables Item.a and Item.b. Now I have two instances of these objects: Item1 and Item2

What I need is something like this:

for (value_1, value_2) in [(Item1.a, Item2.a), (Item1.b, Item2.b)]:
    if value_1 != value_2:
        value_1 = value_2

Of course this one is only an example of more complex problem. The substitution is ok, it finds differences between objects and substitutes them. The problem is, that all the time I'm doing it on copies of those variables, not on object references. As soon as it finish the loop, I can print both Item1 and Item2 and they are the same as before loop.

Is there any possibility to pass references into a loop? I know how to do it with lists, but I could not find an answer to objects.

2
  • I've explained, that was only an example. Actually I'm comparing two instances I receive and update one of them with SOAP request. I don't create them - I can only change their variables. I used Item not to complicate the question and to ask only for what I needed. Commented Jul 28, 2011 at 11:13
  • If you're not comparing "class attributes", but are actually comparing "object attributes", then your question is misleading. Please try to make your question look like your real problem. Commented Jul 28, 2011 at 11:34

1 Answer 1

13

Well, [(Item1.a, Item2.a), (Item1.b, Item2.b)] just creates a list of tuples of some values. Already by creating this you loose the connection to ItemX. Your problem is not related to the loop.

Maybe you want

for prop in ('a', 'b'):
    i2prop = getattr(Item2, prop)
    if getattr(Item1, prop) != i2prop:
        setattr(Item1, prop, i2prop)

Or something similar but with passing ItemX to the loop too:

for x, y, prop in ((Item1, Item2, 'a'), (Item1, Item2, 'b')):
    yprop = getattr(y, prop)
    if getattr(x, prop) != yprop:
        setattr(x, prop, yprop)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was exactly what I was lookinkg for. Even without passing Items into loops.

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.