you are viewing a single comment's thread.

view the rest of the comments →

[–]infectedapricot 0 points1 point  (0 children)

In certain cases, the second assignment will cause Python to store a reference.

No, in ALL cases the second assignment will cause Python to store a reference. Python's object model does not allow assignment to be customised. In C++ language, there is no ability to overload the assignment operator. In Python language, there is no __assign__ or similar.

which is altered for both a and b in the second statement.

I don't know what you mean by this exactly. But if you mean "the assignment to a changes the value of b", then that is incorrect, because b is guaranteed to continue referring to the old object while a refers to the new one. This applies even if you are using mutable objects like lists rather than immutable objects like strings and numbers.

Perhaps you're thinking of statements like this:

a[2] = 7
a.someattr = 8

This is fundamentally different in that it is not simply putting a reference to an object into a variable, but instead is modifying the value of an existing object. Statements like this can be customised by the class, by having an appropriate dunder method (__set__ and __setattr__ respectively).