简体   繁体   English

如何在python中更改for循环中的对象变量

[英]How to change object variables in for loop in python

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 . 假设我有一个带有变量Item.aItem.b的对象Item Now I have two instances of these objects: Item1 and Item2 现在我有两个这些对象的实例: Item1Item2

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. 一旦完成循环,我就可以打印Item1Item2 ,它们与之前的循环相同。

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. 我知道如何使用列表,但我找不到对象的答案。

Well, [(Item1.a, Item2.a), (Item1.b, Item2.b)] just creates a list of tuples of some values. 好吧, [(Item1.a, Item2.a), (Item1.b, Item2.b)]只创建一些值的元组列表。 Already by creating this you loose the connection to ItemX . 通过创建它,您已经失去了与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: 或类似的东西,但也将ItemX传递给循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM