- Python Essentials
- Steven F. Lott
- 239字
- 2021-07-16 13:53:10
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.
- Web應(yīng)用系統(tǒng)開發(fā)實踐(C#)
- The Computer Vision Workshop
- MySQL數(shù)據(jù)庫管理與開發(fā)(慕課版)
- HTML5+CSS3+JavaScript Web開發(fā)案例教程(在線實訓(xùn)版)
- Big Data Analytics
- D3.js 4.x Data Visualization(Third Edition)
- Learning Probabilistic Graphical Models in R
- C/C++程序員面試指南
- 持續(xù)輕量級Java EE開發(fā):編寫可測試的代碼
- 零基礎(chǔ)學(xué)Kotlin之Android項目開發(fā)實戰(zhàn)
- Django 5企業(yè)級Web應(yīng)用開發(fā)實戰(zhàn)(視頻教學(xué)版)
- Nagios Core Administration Cookbook(Second Edition)
- Go語言從入門到精通
- Hands-On Dependency Injection in Go
- HTML5與CSS3權(quán)威指南