Skip to content

Commit 042acb9

Browse files
author
暮晨
committed
EX.Mutating the immutable
1 parent 196763e commit 042acb9

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

README.md

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ So, here we go...
4343
- [> What's wrong with booleans?/布尔你咋了?](#-whats-wrong-with-booleans布尔你咋了)
4444
- [> Class attributes and instance attributes/类属性和实例属性](#-class-attributes-and-instance-attributes类属性和实例属性)
4545
- [> yielding None/生成 None](#-yielding-none生成-none)
46-
- [> Mutating the immutable!](#-mutating-the-immutable)
46+
- [> Mutating the immutable!/强人所难](#-mutating-the-immutable强人所难)
4747
- [> The disappearing variable from outer scope](#-the-disappearing-variable-from-outer-scope)
4848
- [> When True is actually False](#-when-true-is-actually-false)
4949
- [> From filled to None in one instruction...](#-from-filled-to-none-in-one-instruction)
@@ -926,7 +926,7 @@ def some_func(val):
926926
927927
---
928928
929-
### > Mutating the immutable!
929+
### > Mutating the immutable!/强人所难
930930
931931
```py
932932
some_tuple = ("A", "tuple", "with", "values")
@@ -937,7 +937,7 @@ another_tuple = ([1, 2], [3, 4], [5, 6])
937937
```py
938938
>>> some_tuple[2] = "change this"
939939
TypeError: 'tuple' object does not support item assignment
940-
>>> another_tuple[2].append(1000) #This throws no error
940+
>>> another_tuple[2].append(1000) # 这里不出现错误
941941
>>> another_tuple
942942
([1, 2], [3, 4], [5, 6, 1000])
943943
>>> another_tuple[2] += [99, 999]
@@ -946,16 +946,18 @@ TypeError: 'tuple' object does not support item assignment
946946
([1, 2], [3, 4], [5, 6, 1000, 99, 999])
947947
```
948948
949-
But I thought tuples were immutable...
949+
我还以为元组是不可变的呢...
950950
951-
#### 💡 Explanation:
951+
#### 💡 说明:
952+
953+
* 引用 https://docs.python.org/2/reference/datamodel.html
952954
953-
* Quoting from https://docs.python.org/2/reference/datamodel.html
955+
> 不可变序列
956+
不可变序列的对象一旦创建就不能再改变. (如果对象包含对其他对象的引用,则这些其他对象可能是可变的并且可能会被修改; 但是,由不可变对象直接引用的对象集合不能更改.)
954957
955-
> Immutable sequences
956-
An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be modified; however, the collection of objects directly referenced by an immutable object cannot change.)
958+
* `+=` 操作符在原地修改了列表. 元素赋值操作并不工作, 但是当异常抛出时, 元素已经在原地被修改了.
957959
958-
* `+=` operator changes the list in-place. The item assignment doesn't work, but when the exception occurs, the item has already been changed in place.
960+
(译: 对于不可变对象, 这里指tuple, `+=` 并不是原子操作, 而是 `extend` 和 `=` 两个动作, 这里 `=` 操作虽然会抛出异常, 但 `extend` 操作已经修改成功了. 详细解释可以看[这里](https://segmentfault.com/a/1190000010767068))
959961
960962
---
961963

0 commit comments

Comments
 (0)