Skip to content

Commit 30a4347

Browse files
暮晨leisurelicht
暮晨
authored andcommitted
EX.The mysterious key type conversion
1 parent 4a53ca3 commit 30a4347

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

README.md

+10-10
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ So, here we go...
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从有到无)
5050
- [> Subclass relationships/子类关系 *](#-subclass-relationships子类关系-)
51-
- [> The mysterious key type conversion *](#-the-mysterious-key-type-conversion-)
51+
- [> The mysterious key type conversion/神秘的键型转换 *](#-the-mysterious-key-type-conversion神秘的键型转换-)
5252
- [> Let's see if you can guess this?](#-lets-see-if-you-can-guess-this)
5353
- [Section: Appearances are deceptive!](#section-appearances-are-deceptive)
5454
- [> Skipping lines?](#-skipping-lines)
@@ -1120,7 +1120,7 @@ False
11201120
11211121
---
11221122
1123-
### > The mysterious key type conversion *
1123+
### > The mysterious key type conversion/神秘的键型转换 *
11241124
11251125
```py
11261126
class SomeClass(str):
@@ -1135,18 +1135,18 @@ some_dict = {'s':42}
11351135
str
11361136
>>> s = SomeClass('s')
11371137
>>> some_dict[s] = 40
1138-
>>> some_dict # expected: Two different keys-value pairs
1138+
>>> some_dict # 预期: 两个不同的键值对
11391139
{'s': 40}
11401140
>>> type(list(some_dict.keys())[0])
11411141
str
11421142
```
11431143
1144-
#### 💡 Explanation:
1144+
#### 💡 说明:
11451145
1146-
* Both the object `s` and the string `"s"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class.
1147-
* `SomeClass("s") == "s"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class.
1148-
* Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary.
1149-
* For the desired behavior, we can redefine the `__eq__` method in `SomeClass`
1146+
* 由于 `SomeClass` 会从 `str` 自动继承 `__hash__` 方法, 所以 `s` 对象和 `"s"` 字符串的哈希值是相同的.
1147+
* `SomeClass("s") == "s"` `True` 是因为 `SomeClass` 也继承了 `str` 类 `__eq__` 方法.
1148+
* 由于两者的哈希值相同且相等, 所以它们在字典中表示相同的键.
1149+
* 如果想要实现期望的功能, 我们可以重定义 `SomeClass` 的 `__eq__` 方法.
11501150
```py
11511151
class SomeClass(str):
11521152
def __eq__(self, other):
@@ -1156,8 +1156,8 @@ str
11561156
and super().__eq__(other)
11571157
)
11581158
1159-
# When we define a custom __eq__, Python stops automatically inheriting the
1160-
# __hash__ method, so we need to define it as well
1159+
# 当我们自定义 __eq__ 方法时, Python 不会再自动继承 __hash__ 方法
1160+
# 所以我们也需要定义它
11611161
__hash__ = str.__hash__
11621162
11631163
some_dict = {'s':42}

0 commit comments

Comments
 (0)