Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of object references in python

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?

like image 437
aslanides Avatar asked May 08 '15 04:05

aslanides


2 Answers

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.

like image 183
thefourtheye Avatar answered Oct 31 '22 23:10

thefourtheye


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.

like image 26
BrenBarn Avatar answered Nov 01 '22 01:11

BrenBarn