Skip to content

Commit 2aa76bb

Browse files
暮晨ducheng
暮晨
authored and
ducheng
committed
EX.The mysterious key type conversion
1 parent 54a418c commit 2aa76bb

File tree

1 file changed

+10
-10
lines changed

1 file changed

+10
-10
lines changed

README.md

Lines changed: 10 additions & 10 deletions
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)
@@ -1115,7 +1115,7 @@ False
11151115
11161116
---
11171117
1118-
### > The mysterious key type conversion *
1118+
### > The mysterious key type conversion/神秘的键型转换 *
11191119
11201120
```py
11211121
class SomeClass(str):
@@ -1130,18 +1130,18 @@ some_dict = {'s':42}
11301130
str
11311131
>>> s = SomeClass('s')
11321132
>>> some_dict[s] = 40
1133-
>>> some_dict # expected: Two different keys-value pairs
1133+
>>> some_dict # 预期: 两个不同的键值对
11341134
{'s': 40}
11351135
>>> type(list(some_dict.keys())[0])
11361136
str
11371137
```
11381138
1139-
#### 💡 Explanation:
1139+
#### 💡 说明:
11401140
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__` 方法.
11451145
```py
11461146
class SomeClass(str):
11471147
def __eq__(self, other):
@@ -1151,8 +1151,8 @@ str
11511151
and super().__eq__(other)
11521152
)
11531153
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+
# 所以我们也需要定义它
11561156
__hash__ = str.__hash__
11571157
11581158
some_dict = {'s':42}

0 commit comments

Comments
 (0)