3 回答

TA貢獻(xiàn)1869條經(jīng)驗(yàn) 獲得超4個(gè)贊
什么?浮標(biāo)是不變的?但我不能
x = 5.0
x += 7.0
print x # 12.0
那不是“啞巴”x嗎?
你同意字符串是不可變的,對(duì)吧?但你也可以做同樣的事。
s = 'foo'
s += 'bar'
print s # foobar
變量的值會(huì)發(fā)生變化,但它會(huì)通過(guò)更改變量引用的內(nèi)容而改變??勺冾愋涂梢赃@種方式改變,而且它可以。也改變“就位”。
這就是不同之處。
x = something # immutable type
print x
func(x)
print x # prints the same thing
x = something # mutable type
print x
func(x)
print x # might print something different
x = something # immutable type
y = x
print x
# some statement that operates on y
print x # prints the same thing
x = something # mutable type
y = x
print x
# some statement that operates on y
print x # might print something different
具體實(shí)例
x = 'foo'
y = x
print x # foo
y += 'bar'
print x # foo
x = [1, 2, 3]
y = x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]
def func(val):
val += 'bar'
x = 'foo'
print x # foo
func(x)
print x # foo
def func(val):
val += [3, 2, 1]
x = [1, 2, 3]
print x # [1, 2, 3]
func(x)
print x # [1, 2, 3, 3, 2, 1]

TA貢獻(xiàn)1817條經(jīng)驗(yàn) 獲得超6個(gè)贊
TypeError
>>> s = "abc">>>id(s)4702124>>> s[0] 'a'>>> s[0] = "o"Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: 'str' object does not support item assignment >>> s = "xyz">>>id(s)4800100>>> s += "uvw">>>id(s)4800500
>>> i = [1,2,3]>>>id(i)2146718700>>> i[0] 1>>> i[0] = 7>>> id(i)2146718700

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超4個(gè)贊
數(shù)字: int()
,float()
,complex()
不可變序列: str()
,tuple()
,frozenset()
,bytes()
可變序列: list()
,bytearray()
設(shè)置類型: set()
制圖類型: dict()
類,類實(shí)例 等。
id()
>>> i = 1>>> id(i)***704>>> i += 1>>> i2>>> id(i)***736 (different from ***704)
>>> a = [1]>>> id(a)***416>>> a.append(2)>>> a[1, 2]>>> id(a)***416 (same with the above id)
添加回答
舉報(bào)