3 回答
![?](http://img1.sycdn.imooc.com/54584ed2000152a202200220-100-100.jpg)
TA贡献1869条经验 获得超4个赞
什么?浮标是不变的?但我不能
x = 5.0
x += 7.0
print x # 12.0
那不是“哑巴”x吗?
你同意字符串是不可变的,对吧?但你也可以做同样的事。
s = 'foo'
s += 'bar'
print s # foobar
变量的值会发生变化,但它会通过更改变量引用的内容而改变。可变类型可以这种方式改变,而且它可以。也改变“就位”。
这就是不同之处。
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
具体实例
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]
![?](http://img1.sycdn.imooc.com/545864490001b5bd02200220-100-100.jpg)
TA贡献1817条经验 获得超6个赞
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
![?](http://img1.sycdn.imooc.com/5333a01a0001ee5302000200-100-100.jpg)
TA贡献1829条经验 获得超4个赞
数字: int()
,float()
,complex()
不可变序列: str()
,tuple()
,frozenset()
,bytes()
可变序列: list()
,bytearray()
设置类型: set()
制图类型: dict()
类,类实例 等。
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)
添加回答
举报