3 回答

TA贡献1946条经验 获得超4个赞
>>> 1
1
>>> id(1)
140413541333480
>>> x = 1
>>> id(x)
140413541333480
>>> z = 1
>>> id(z)
140413541333480
>>> y = x
>>> id(y)
140413541333480
>>>
出于优化的目的,只有 1 的单个副本,并且所有变量都引用它。
现在,python 中的整数和字符串是不可变的。每次定义一个新的时,都会生成一个新的引用/ID。
>>> x = 1 # x points to reference (id) of 1
>>> y = x # now y points to reference (id) of 1
>>> x = 5 # x now points to a new reference: id(5)
>>> y # y still points to the reference of 1
1
>>> x = "foo"
>>> y = x
>>> x = "bar"
>>> y
'foo'
>>>
列表、字典是可变的,也就是说,你可以在同一个引用处修改值。
>>> x = [1, 'foo']
>>> id(x)
4493994032
>>> x.append('bar')
>>> x
[1, 'foo', 'bar']
>>> id(x)
4493994032
>>>
因此,如果您的变量指向一个引用并且该引用包含一个可变值并且该值已更新,则该变量将反映最新值。
如果引用被覆盖,它将指向引用所指向的任何内容。
>>> x = [1, 'foo']
>>> y = x # y points to reference of [1, 'foo']
>>> x = [1, 'foo', 'bar'] # reference is overridden. x points to reference of [1, 'foo', 'bar']. This is a new reference. In memory, we now have [1, 'foo'] and [1, 'foo', 'bar'] at two different locations.
>>> y
[1, 'foo']
>>>
>>> x = [1, 'foo']
>>> y = x
>>> x.append(10) # reference is updated
>>> y
[1, 'foo', 10]
>>> x = {'foo': 10}
>>> y = x
>>> x = {'foo': 20, 'bar': 20}
>>> y
{'foo': 10}
>>> x = {'foo': 10}
>>> y = x
>>> x['bar'] = 20 # reference is updated
>>> y
{'foo': 10, 'bar': 20}
>>>
您的问题的第二部分(通用语言)太宽泛了,Stackoverflow 不是解决这个问题的合适论坛。请对您感兴趣的语言进行研究 - 每个语言组及其论坛上都有大量可用信息。

TA贡献1876条经验 获得超5个赞
x = 5
id(x) = 94516543976904 // Here it will create a new object
y = x
id(y) = 94516543976904 // Here it will not create a new object instead it will refer to x (because both of them have same values).
x = 4
id(x) = 94516543976928 // Here we are changing the value of x. A new object will be created because integer are immutable.
添加回答
举报