Python变量与其他语言(例如C)中的变量完全不同。
在许多其他语言中,变量是内存中位置的名称。 在这些语言中,不同种类的变量可以引用不同种类的位置,并且同一位置可以使用多个名称。 在大多数情况下,给定的内存位置可能会不时更改数据。 还有一些间接引用内存位置的方法(int *p将包含该地址,并且在该地址的内存位置中有一个整数。) 变量是位置。 这些语言中的变量分配实际上是“查找此变量的位置,并将此数据复制到该位置”
Python不能那样工作。 在python中,实际对象位于某个内存位置,变量就像位置的标记。 Python以与管理变量不同的方式管理存储的值。 本质上,在python中的赋值意味着“查找该变量的信息,忘记它已经引用的位置,并用这个新位置替换它”。 没有数据被复制。
像python一样工作的语言的一个共同特征(与我们之前讨论的第一种相反)是某些对象以特殊的方式进行管理; 缓存相同的值,这样它们就不会占用额外的内存,并且可以很容易地比较它们(如果它们具有相同的地址,则它们相等)。 这个过程称为实习。 尽管不是动态创建的字符串,但所有python字符串文字都可以使用intern(除了其他几种类型)。
在您的确切代码中,语义对话框将是:
# before anything, since 'cat' is a literal constant, add it to the intern cache
>>> id('cat') # grab the constant 'cat' from the intern cache and look up
# it's address
5181152
>>> a = 'cat' # grab the constant 'cat' from the intern cache and
# make the variable "a" point to it's location
>>> b = 'cat' # do the same thing with the variable "b"
>>> id(a) # look up the object "a" currently points to,
# then look up that object's address
5181152
>>> id(b) # look up the object "b" currently points to,
# then look up that object's address
5181152