官术网_书友最值得收藏!

The consequences of immutability

Python has two broad flavors of objects: mutable and immutable. A mutable object has an internal state that can be updated by using operators or method functions. An immutable object's state cannot be changed.

The canonical examples of immutable objects are the numbers. The number 2 must always have a single, immutable value midway between 1 and 3. We can't change the state of 2 to make it 3 without making a mockery of the idea of mathematical truth.

In Chapter 6, More Complex Data Types, we'll look at a number of mutable data structures. The most important three mutable collections are set, list, and dict. These objects can have items added, and removed; we can change the state of the object.

In addition to numbers being immutable, three other common structures are also immutable: str, bytes, and tuple. Because strings and bytes are immutable, the string manipulation methods will always create a new string object from one or more existing string objects.

This means we cannot mutate characters or substrings within a longer string. We might think we need to attempt something like this:

>>> word="vokalizers"
>>> word[2]= "c"

But this can't work because a string object is immutable. We always build new strings from the old string's parts. We do it like this:

>>> word= word[:2]+"c"+word[3:]

This works by extracting pieces of the original string and including new characters mixed with the old.

主站蜘蛛池模板: 晋城| 镇巴县| 永春县| 昆明市| 安福县| 柳河县| 巴楚县| 峨眉山市| 芒康县| 湘潭市| 隆化县| 长宁县| 云和县| 酒泉市| 宜黄县| 清苑县| 砚山县| 天镇县| 秦安县| 丰镇市| 新昌县| 中卫市| 平武县| 金昌市| 肥乡县| 安仁县| 恩平市| 都安| 怀安县| 达尔| 舒兰市| 昌图县| 南城县| 和龙市| 汤阴县| 丰台区| 皋兰县| 青海省| 礼泉县| 宽城| 枞阳县|