相关疑难解决方法(0)

不可变容器内的可变类型

我对修改元组成员有点困惑.以下不起作用:

>>> thing = (['a'],)
>>> thing[0] = ['b']
TypeError: 'tuple' object does not support item assignment
>>> thing
(['a'],)
Run Code Online (Sandbox Code Playgroud)

但这确实有效:

>>> thing[0][0] = 'b'
>>> thing
(['b'],)
Run Code Online (Sandbox Code Playgroud)

还有效:

>>> thing[0].append('c')
>>> thing
(['b', 'c'],)
Run Code Online (Sandbox Code Playgroud)

不起作用,并且有效(嗯?!):

>>> thing[0] += 'd'
TypeError: 'tuple' object does not support item assignment
>>> thing
(['b', 'c', 'd'],)
Run Code Online (Sandbox Code Playgroud)

看似与以前相同,但有效:

>>> e = thing[0]
>>> e += 'e'
>>> thing
(['b', 'c', 'd', 'e'],)
Run Code Online (Sandbox Code Playgroud)

那么,当你能够并且不能修改元组内的某些内容时,游戏的规则到底是什么?它似乎更像禁止使用赋值成员的赋值运算符,但最后两个案例让我感到困惑.

python tuples list mutable immutability

10
推荐指数
2
解决办法
593
查看次数

标签 统计

immutability ×1

list ×1

mutable ×1

python ×1

tuples ×1