最好不要把可变对象放在元组内

最好不要把可变对象放在元组内

t = (1, 2, [3, 4])
t[2] += [5, 6]

对于这种情况,一般人可能会想,tuple是不可变对象,所以会抛出throw typeError异常,但是结果如下:

>>> t = (1, 2, [3, 4])
>>> t[2] += [5, 6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> t
(1, 2, [3, 4, 5, 6])

但是如果用

t[2].extend([5, 6])

能避免这个异常

>>> t = (1, 2, [3, 4]) 
>>> t[2].extend([5, 6])
>>> t
(1, 2, [3, 4, 5, 6])

猜你喜欢

转载自blog.csdn.net/tlssnp/article/details/114222668