There is this code:
# assignment behaviour for integer
a = b = 0
print a, b # prints 0 0
a = 4
print a, b # prints 4 0 - different!
# assignment behaviour for class object
class Klasa:
def __init__(self, num):
self.num = num
a = Klasa(2)
b = a
print a.num, b.num # prints 2 2
a.num = 3
print a.num, b.num # prints 3 3 - the same!
Questions:
- Why assignment operator works differently for fundamental type and
class object (for fundamental types it copies by value, for class object it copies by reference)? - How to copy class objects only by value?
- How to make references for fundamental types like in C++ int& b = a?
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 newintobject is created with value0and two references to it are created (one isaand another isb). These two variables point to the same object (the integer which we created). Now, we runa = 4. A newintobject of value4is created andais made to point to that. This means, that the number of references to4is one and the number of references to0has been reduced by one.Compare this with
a = 4in C where the area of memory whicha“points” to is written to.a = b = 4in C means that4is written to two pieces of memory – one foraand another forb.Now the second case,
a = Klass(2)creates an object of typeKlass, increments its reference count by one and makesapoint to it.b = asimply takes whatapoints to , makesbpoint to the same thing and increments the reference count of the thing by one. It’s the same as what would happen if you dida = b = Klass(2). Trying to printa.numandb.numare the same since you’re dereferencing the same object and printing an attribute value. You can use theidbuiltin function to see that the object is the same (id(a)andid(b)will return the same identifier). Now, you change the object by assigning a value to one of it’s attributes. Sinceaandbpoint to the same object, you’d expect the change in value to be visible when the object is accessed viaaorb. And that’s exactly how it is.Now, for the answers to your questions.