How Python Sees Variables

Becoming a Python Developer (6 Part Series)

1 Python: Preamble
2 The bare-bones of a Python program
2 more parts…
3 Python: Memory Management
4 Comments and Docstrings in Python
5 How Python Sees Variables
6 Mastering Datatypes in Python

In programming languages like C and Java, the concept of a variable is related to a memory location. Hence, often a variable is defined as a named memory location. Let us visualize this with an example, say we have the equation

int a = 1;

Enter fullscreen mode Exit fullscreen mode

This may be viewed as a memory box:
图片[1]-How Python Sees Variables - 拾光赋-拾光赋
Say we now store another value using the same variable

a = 2;

Enter fullscreen mode Exit fullscreen mode

This may be viewed as an updated memory box:
图片[2]-How Python Sees Variables - 拾光赋-拾光赋
Let us now store the value of this variable into another

int b = a;

Enter fullscreen mode Exit fullscreen mode

This creates another memory box as follows:
图片[3]-How Python Sees Variables - 拾光赋-拾光赋
This is basically how other programming languages visualize variables. We can simply say that the “memory location” is emphasized which contains a “value“. However, Python views variables as “tags” which are referenced (or tied) to some “value” (or object).

Let us visualize the above examples once again, say we have the equation

a = 1

Enter fullscreen mode Exit fullscreen mode

This may be viewed as the value or object having priority, to which a tag is assigned:
图片[4]-How Python Sees Variables - 拾光赋-拾光赋
Say we now store another value using the same variable

a = 2

Enter fullscreen mode Exit fullscreen mode

In this case, the tag is simply changed to the new value, and the previous value (now unreferenced) is removed by the garbage collector:
图片[5]-How Python Sees Variables - 拾光赋-拾光赋
Let us now store the value of this variable into another

b = a

Enter fullscreen mode Exit fullscreen mode

In this case, another tag is created that references to the same object:
图片[6]-How Python Sees Variables - 拾光赋-拾光赋
Hence, only one memory is referenced by two names.

So to conclude, other languages have variables, while Python has ‘tags’ to represent the values (or objects). This method allows Python to utilize memory efficiently, and this visualization helps in understanding variables in Python.

Becoming a Python Developer (6 Part Series)

1 Python: Preamble
2 The bare-bones of a Python program
2 more parts…
3 Python: Memory Management
4 Comments and Docstrings in Python
5 How Python Sees Variables
6 Mastering Datatypes in Python

原文链接:How Python Sees Variables

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容