How to change object variables in for loop in python

I'm not sure whether it is an easy problem with a simple solution or something that needs to be digged a little deeper.

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

I need 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 is just an example of a more complex problem. Substitution is fine; it finds differences between objects and replaces them. The problem is that all the time I do this on copies of these variables, and not on object references. Once it completes the loop, I can print both Item1 and Item2 , and they will be the same as before the loop.

Is it possible to pass links to the loop? I know how to do this with lists, but I could not find the answer to the objects.

+4
source share
1 answer

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

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:

 for x, y, prop in ((Item1, Item2, 'a'), (Item1, Item2, 'b')): yprop = getattr(y, prop) if getattr(x, prop) != yprop: setattr(x, prop, yprop) 
+9
source

All Articles