【发布时间】:2019-02-01 21:08:57
【问题描述】:
目前,我对 Python 的内置类型进行了一些研究。我很困惑调用什么方法来检查一个键是否在字典中。例如,如果我检查 int 类型的键是否在字典中,则只有在 dictionary.keys() 包含它时才会在后台调用 __eq__() 方法。如果不是 __eq__() 则不会被调用。
这是一个代码示例:
dict = {
1: "Hello",
2: "World",
4: "Foo"
}
assert 1 in dict.keys() # the __eq__() method of int is invoked
assert not(3 in dict.keys()) # no __eq__() method of int is invoked
我知道,字典包含一个哈希(键)、键和值的元组。但是我有点困惑,为什么在第二个断言中没有调用__eq__()。
为了测试这种行为,我从int 继承并设置了一些断点。这是我的自定义 int 类的摘录:
tint(int):
def __new__(cls, value, *args, **kw):
return super(tint, cls).__new__(cls, value)
def __init__(self, value):
super().__init__()
def __eq__(self, other):
return super().__eq__(other) # with breakpoints
def __ne__(self, other):
return super().__ne__(other) # with breakpoints
def __hash__(self):
return tint(super().__hash__()) # with breakpoints
我在 Ubuntu 18.04.1 LTS 上使用 Python 版本 3.6.5。
【问题讨论】:
标签: python python-3.x hashmap built-in