@@ -48,7 +48,7 @@ So, here we go...
48
48
- [ > When True is actually False/真亦假] ( #-when-true-is-actually-false真亦假 )
49
49
- [ > From filled to None in one instruction.../从有到无...] ( #-from-filled-to-none-in-one-instruction从有到无 )
50
50
- [ > 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神秘的键型转换 - )
52
52
- [ > Let's see if you can guess this?] ( #-lets-see-if-you-can-guess-this )
53
53
- [ Section: Appearances are deceptive!] ( #section-appearances-are-deceptive )
54
54
- [ > Skipping lines?] ( #-skipping-lines )
@@ -1120,7 +1120,7 @@ False
1120
1120
1121
1121
---
1122
1122
1123
- ### > The mysterious key type conversion *
1123
+ ### > The mysterious key type conversion/神秘的键型转换 *
1124
1124
1125
1125
```py
1126
1126
class SomeClass(str):
@@ -1135,18 +1135,18 @@ some_dict = {'s':42}
1135
1135
str
1136
1136
>>> s = SomeClass('s')
1137
1137
>>> some_dict[s] = 40
1138
- >>> some_dict # expected: Two different keys-value pairs
1138
+ >>> some_dict # 预期: 两个不同的键值对
1139
1139
{'s': 40}
1140
1140
>>> type(list(some_dict.keys())[0])
1141
1141
str
1142
1142
```
1143
1143
1144
- #### 💡 Explanation :
1144
+ #### 💡 说明 :
1145
1145
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__` 方法.
1150
1150
```py
1151
1151
class SomeClass(str):
1152
1152
def __eq__(self, other):
@@ -1156,8 +1156,8 @@ str
1156
1156
and super().__eq__(other)
1157
1157
)
1158
1158
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
+ # 所以我们也需要定义它
1161
1161
__hash__ = str.__hash__
1162
1162
1163
1163
some_dict = {'s':42}
0 commit comments