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.
添加回答
舉報