Assumption before you start is — that you understand below concepts, if not — its worth a quick detour to below links:

Proceed if you know — what happens as a single variable is assigned references to objects? Else read above three articles real quick and come back.

If you know what happens as a single variable is assigned reference to an object then — let’s introduce another variable into our interaction and watch what happens to its names and objects:

>>> x = 10
>>> y = x

If above two statements are executed in python — something like this happens.

The second command causes Python to create the variable y, the variable x is being used and not assigned here, so it is replaced with the object it references (10), and y is made to reference that object. The net effect is that the variables x and y wind up referencing the same object (that is, pointing to the same chunk of memory).

This scenario in Python — with multiple names referencing the same object — is usually called a shared reference or a shared object. Note that the names x and y are not linked to each other directly when this happens, in fact — there is no way to ever link a variable to another variable in Python! Rather, both variables point to the same object via their references.

Next, suppose we extend the example with one more statement:

>>> x = 10
>>> y = x
>>> x = 'bharath'

As with all Python assignments, this statement simply makes a new object to represent the string value ‘bharath’ and sets a to reference this new object. It does not, however, change the value of y, y still references the original object, the integer 10. The resulting reference structure, looks something like this.

Image for post

The same sort of thing would happen if we changed b to ‘bharath’ instead — the assignment would change only y, not x. This behavior also occurs if there are no type differences at all. For example, consider these three statements:

>>> x = 10
   >>> y = x
   >>> x = x + 2

In this sequence, the same events transpire. Python makes the variable x reference the object 10 and makes y reference the same object as x, the last assignment then sets a to a completely different object (in this case, the integer 12, which is the result of the + expression). It does not change y as a side effect. In fact, there is no way to ever overwrite the value of the object 10 — as integers are immutable and thus can never be changed in place.

#conceptual-understanding #data-science #python #analytics-vidhya

Object reference model in Python — a conceptual understanding.
2.30 GEEK