为什么 python 字符串和元组是不可变的?

2022-01-19 00:00:00 python string tuples immutability

问题描述

我不确定为什么字符串和元组是不可变的;使它们不可变的优点和缺点是什么?

I am not sure why strings and tuples were made to be immutable; what are the advantages and disadvantage of making them immutable?


解决方案

一个是性能:知道一个字符串是不可变的,因此很容易在施工时布置——固定不变的存储要求.这也是其中之一区分的原因元组和列表.这也允许安全重用字符串的实现对象.例如,CPython实现使用预分配单字符串的对象,并且通常会返回原件用于字符串操作的字符串不会改变内容.

One is performance: knowing that a string is immutable makes it easy to lay it out at construction time — fixed and unchanging storage requirements. This is also one of the reasons for the distinction between tuples and lists. This also allows the implementation to safely reuse string objects. For example, the CPython implemenation uses pre-allocated objects for single-character strings, and usually returns the original string for string operations that doesn’t change the content.

另一个是Python中的字符串被认为是基本的";作为数字.再多的活动也不会将值 8 更改为其他值,在 Python 中,没有多少活动将字符串八"更改为还有什么.

The other is that strings in Python are considered as "elemental" as numbers. No amount of activity will change the value 8 to anything else, and in Python, no amount of activity will change the string "eight" to anything else.

https://web.archive.org/web/20201031092707/http://effbot.org/pyfaq/why-are-python-strings-immutable.htm

相关文章