你真的了解python tuple不可变吗

最近遇到个有关tuple的面试题,挺有意思的。

# 下面会输出什么?为什么
In [18]: tu = (1, [1, 2])
In [19]: tu[1].append(3)
In [20]: print(tu)
(1, [1, 2, 3])

tupple不可变是指对象不可变,不可以对tuple中的元素进行赋值操作。它所包含的元素的可变性取决于该元素的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    In [22]: tu[1] = [1,2,3,4]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-1e2059dd0201> in <module>()
----> 1 tu[1] = [1,2,3,4]

TypeError: 'tuple' object does not support item assignment

In [23]: print(tu) #报错,赋值操作未成功
(1, [1, 2, 3])

In [24]: tu[1] += [1,2,3,4]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-e1dc81ae6e45> in <module>
----> 1 tu[1] += [1,2,3,4]

TypeError: 'tuple' object does not support item assignment

In [25]: tu # 报错,虽然报错,但操作成功了
Out[26]: (1, [1, 2, 3, 1, 2, 3, 4])


In [27]: class A:
...: a = 1
...:

In [28]: a = A()
In [29]: t = (1, a)

In [30]: t[1].a = 2

In [31]: print(t[1].a)
2