0

Suppose I have the following code:

class C:
    def __init__(self, data):
        self.data=data #default

x=C(1)
y=C(2)

for obj in [x, y]:
    obj.data+=1 # manipulate object referenced to by x or y

    obj=C(999) # create a new object
    print obj.data

print x.data
print y.data

the output is:

999 999 2 3

If I understand correctly, in the for loop the objects are manipulated in obj.data+=1but when creating a new object in obj=C(999) the temporary alias obj and original x and y are no longer pointing to same object.

So my question: how to iterate through multiple known objects and be able to assign to them new objects? I my example it would mean that x and y will point to newly created objects in the for loop so the output will be:

999 999 999 999

Max Segal
  • 1,955
  • 1
  • 24
  • 53
  • What are you trying to do here? why `obj = C(999)` in the for loop? – styvane Jun 14 '16 at 20:43
  • just create a new object and assign its reference to temporary variable 'obj' – Max Segal Jun 14 '16 at 20:46
  • And that's what you do. It's not clear why you thought that would relate at all to the objects in the list that were previously assigned to that variable by the `for` loop. Please read http://nedbatchelder.com/text/names.html – jonrsharpe Jun 14 '16 at 20:48
  • `obj` is changed each iteration of the `for` loop. The instances of `C` the original `x` and `y` refer to are changed by the `obj.data+=1` when `obj` is assigned to refer to them. Just name any others created inside the loop something other than `obj`, like `foo = C(999)` and/or `bar = C(999)`. – martineau Jun 14 '16 at 20:54

1 Answers1

2

You are actually looping a list you just created. You keep no reference of the list afterwards. If you do this in function callings you certainlly won't be able to change variables in another scope.

You can however, change the list you received (as argument, in an hipotetical function). Try something like this:

list = [x, y]
for i, obj in enumerate(list):
    list[i]=C(999)
    print list[i].data

print list[0].data
print list[1].data
Hugo Mota
  • 11,200
  • 9
  • 42
  • 60
  • but how can assign new objects to x and y with iteration through them using a for loop? – Max Segal Jun 14 '16 at 21:18
  • I don't know how to do that. I don't even know if it is possible or why would you need such thing. Are you trying this because of something you can do in some other language? Try to edit your question with some more details of what are you trying to achieve. Maybe someone can come up with something then. Meanwhile you can refer to a similar question: http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop – Hugo Mota Jun 15 '16 at 12:19