3 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
>>> 1
1
>>> id(1)
140413541333480
>>> x = 1
>>> id(x)
140413541333480
>>> z = 1
>>> id(z)
140413541333480
>>> y = x
>>> id(y)
140413541333480
>>>
出于優(yōu)化的目的,只有 1 的單個(gè)副本,并且所有變量都引用它。
現(xiàn)在,python 中的整數(shù)和字符串是不可變的。每次定義一個(gè)新的時(shí),都會(huì)生成一個(gè)新的引用/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'
>>>
列表、字典是可變的,也就是說(shuō),你可以在同一個(gè)引用處修改值。
>>> x = [1, 'foo']
>>> id(x)
4493994032
>>> x.append('bar')
>>> x
[1, 'foo', 'bar']
>>> id(x)
4493994032
>>>
因此,如果您的變量指向一個(gè)引用并且該引用包含一個(gè)可變值并且該值已更新,則該變量將反映最新值。
如果引用被覆蓋,它將指向引用所指向的任何內(nèi)容。
>>> 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}
>>>
您的問(wèn)題的第二部分(通用語(yǔ)言)太寬泛了,Stackoverflow 不是解決這個(gè)問(wèn)題的合適論壇。請(qǐng)對(duì)您感興趣的語(yǔ)言進(jìn)行研究 - 每個(gè)語(yǔ)言組及其論壇上都有大量可用信息。

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個(gè)贊
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.
添加回答
舉報(bào)