Assignment of objects and fundamental types [duplicate]

This is a stumbling block for many Python users. The object reference semantics are different from what C programmers are used to.

Let’s take the first case. When you say a = b = 0, a new int object is created with value 0 and two references to it are created (one is a and another is b). These two variables point to the same object (the integer which we created). Now, we run a = 4. A new int object of value 4 is created and a is made to point to that. This means, that the number of references to 4 is one and the number of references to 0 has been reduced by one.

Compare this with a = 4 in C where the area of memory which a “points” to is written to. a = b = 4 in C means that 4 is written to two pieces of memory – one for a and another for b.

Now the second case, a = Klass(2) creates an object of type Klass, increments its reference count by one and makes a point to it. b = a simply takes what a points to , makes b point to the same thing and increments the reference count of the thing by one. It’s the same as what would happen if you did a = b = Klass(2). Trying to print a.num and b.num are the same since you’re dereferencing the same object and printing an attribute value. You can use the id builtin function to see that the object is the same (id(a) and id(b) will return the same identifier). Now, you change the object by assigning a value to one of it’s attributes. Since a and b point to the same object, you’d expect the change in value to be visible when the object is accessed via a or b. And that’s exactly how it is.

Now, for the answers to your questions.

  1. The assignment operator doesn’t work differently for these two. All it does is add a reference to the RValue and makes the LValue point to it. It’s always “by reference” (although this term makes more sense in the context of parameter passing than simple assignments).
  2. If you want copies of objects, use the copy module.
  3. As I said in point 1, when you do an assignment, you always shift references. Copying is never done unless you ask for it.

Leave a Comment