@@ -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 )
@@ -1115,7 +1115,7 @@ False
1115
1115
1116
1116
---
1117
1117
1118
- ### > The mysterious key type conversion *
1118
+ ### > The mysterious key type conversion/神秘的键型转换 *
1119
1119
1120
1120
```py
1121
1121
class SomeClass(str):
@@ -1130,18 +1130,18 @@ some_dict = {'s':42}
1130
1130
str
1131
1131
>>> s = SomeClass('s')
1132
1132
>>> some_dict[s] = 40
1133
- >>> some_dict # expected: Two different keys-value pairs
1133
+ >>> some_dict # 预期: 两个不同的键值对
1134
1134
{'s': 40}
1135
1135
>>> type(list(some_dict.keys())[0])
1136
1136
str
1137
1137
```
1138
1138
1139
- #### 💡 Explanation :
1139
+ #### 💡 说明 :
1140
1140
1141
- * Both the object `s` and the string `"s"` hash to the same value because `SomeClass` inherits the `__hash__` method of `str` class .
1142
- * `SomeClass("s") == "s"` evaluates to `True` because `SomeClass` also inherits `__eq__` method from `str` class .
1143
- * Since both the objects hash to the same value and are equal, they are represented by the same key in the dictionary .
1144
- * For the desired behavior, we can redefine the `__eq__` method in `SomeClass`
1141
+ * 由于 `SomeClass` 会从 `str` 自动继承 `__hash__` 方法, 所以 `s` 对象和 `"s"` 字符串的哈希值是相同的 .
1142
+ * 而 `SomeClass("s") == "s"` 为 `True` 是因为 `SomeClass` 也继承了 `str` 类 `__eq__` 方法 .
1143
+ * 由于两者的哈希值相同且相等, 所以它们在字典中表示相同的键 .
1144
+ * 如果想要实现期望的功能, 我们可以重定义 `SomeClass` 的 `__eq__` 方法.
1145
1145
```py
1146
1146
class SomeClass(str):
1147
1147
def __eq__(self, other):
@@ -1151,8 +1151,8 @@ str
1151
1151
and super().__eq__(other)
1152
1152
)
1153
1153
1154
- # When we define a custom __eq__, Python stops automatically inheriting the
1155
- # __hash__ method, so we need to define it as well
1154
+ # 当我们自定义 __eq__ 方法时 , Python 不会再自动继承 __hash__ 方法
1155
+ # 所以我们也需要定义它
1156
1156
__hash__ = str.__hash__
1157
1157
1158
1158
some_dict = {'s':42}
0 commit comments