I'm aware that this question has already been asked here in one form or another, but none of the answers address the behaviour I'm seeing. I'm given to understand that a list of objects should only hold references to those objects. What I observe seems to contract this:
class Foo(object):
def __init__(self,val):
self.value=val
a = Foo(2)
b = [a]
print b[0].value
a = Foo(3)
print b[0].value
I expect to see 2
printed first, then 3
, since I expect b[0]
to point to a
, which is now a new object. Instead I see 2
and 2
. What am I missing here?
In Python, assignment operator binds the result of the right hand side expression to the name from the left hand side expression.
So, when you say
a = Foo(2)
b = [a]
you have created a Foo
object and refer it with a
. Then you create a list b
with the reference to the Foo
object (a
). That is why b[0].value
prints 2
.
But,
a = Foo(3)
creates a new Foo
object and refers that with the name a
. So, now a
refers to the new Foo
object not the old object. But the list still has reference to the old object only. That is why it still prints 2.
b[0]
points to the object you initially created with Foo(2)
. When you do a = Foo(3)
, you create a new object and call it a
. You did not change b
in any way.
The behavior is because of exactly what you said: b
holds a reference to an object. It does not hold hold a reference to the name you used to refer to that object. So the object in b[0]
does not know anything about any variable called a
. Assigning a new value to a
has no effect on b
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With