为什么在Python中元组不可变? [英] Why tuple is not mutable in Python?
本文介绍了为什么在Python中元组不可变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
为什么将python字符串和元组变成不可变的?
Possible Duplicate:
Why are python strings and tuples are made immutable?
什么样的低级设计使元组在Python中不可变?为什么此功能有用?
What lower-level design makes tuple not mutable in Python? Why this feature is useful?
推荐答案
一些原因:
- Mutable objects like lists cannot be used as dictionary keys or set members in Python, since they are not hashable. If lists were given
__hash__
methods based on their contents, the values returned could change as the contents change, which violates the contract for hash values. - If Python only had mutable sequences, constructors which accepted sequences would often need to copy them to ensure that the sequences couldn't be modified by other code. Constructors can avoid defensive copying by only accepting tuples. Better yet, they can pass sequence arguments through the
tuple
method which will copy only when necessary.
这篇关于为什么在Python中元组不可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文