本文介绍了为什么在Python中元组不可变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么样的低级设计使元组在Python中不可变?为什么此功能有用?
What lower-level design makes tuple not mutable in Python? Why this feature is useful?
推荐答案
一些原因:
- 像列表这样的可变对象不能用作字典键或Python中的集合成员,因为它们不是可哈希.如果根据列表的内容为列表赋予
__hash__
方法,则返回的值可能会随着内容的变化而变化,这违反了哈希值的约定. - 如果Python仅具有可变序列,则接受序列的构造函数通常需要复制它们,以确保其他代码无法修改该序列.构造函数可以仅接受元组来避免防御性复制.更好的是,它们可以通过
tuple
方法传递序列参数,该方法仅在必要时复制.
- 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中元组不可变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!