Can someone explain this python behavior to me? -


can explain behavior? when run code, prints 10, 20. why list_of_classes being changed though changed value of bob? shouldn't have update list 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 

your lists contain references objects, not copies.

list_of_classes[0] reference same object bob references. can create more references same object , attribute change visible through 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 bob true 

if wanted add copies of class list, use copy module create deep copy of instance:

>>> import copy >>> robert = copy.deepcopy(bob) >>> robert.x 20 >>> bob.x = 30 >>> robert.x 20 >>> robert bob false 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -