1

Can someone explain this behavior? When I run the code, it prints 10, then 20. Why is list_of_classes being changed even though I only changed the value of bob? Shouldn't I have to update the list with the new values?

class wooo():
    def __init__(self,x,y,name):
        self.x=x
        self.y=y
        self.name=name

bob=wooo(10,10,"bob")
joe=wooo(10,10,"joe")
list_of_classes=[bob,joe]
print(list_of_classes[0].x)
bob.x=20
print(list_of_classes[0].x)

Actual Output

10
20

Expected Output

10
10

1 Answer 1

7

Your lists contain references to the objects, not copies.

list_of_classes[0] is a reference to the same object that bob references. You can create more references to the same object and the attribute change would be visible through all those references:

>>> class wooo():
...     def __init__(self,x,y,name):
...         self.x=x
...         self.y=y
...         self.name=name
... 
>>> bob=wooo(10,10,"bob")
>>> guido = bob
>>> guido.x
10
>>> guido.x = 20
>>> bob.x
20
>>> guido is bob
True

If you wanted to add copies of a class to the list, use the copy module to create a deep copy of your instance:

>>> import copy
>>> robert = copy.deepcopy(bob)
>>> robert.x
20
>>> bob.x = 30
>>> robert.x
20
>>> robert is bob
False
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.