python字典中的键

2024-09-28 19:02:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到的问题分布在许多源文件中,我试图以简单的线性格式重现该问题的尝试失败了。尽管如此,我遇到的问题还是简单地描述了一下

我有一个类Path,我为它实现了__hash____eq__

我在dict中有一个类型为Path的项,如

path in list(thedict)
>> True

我验证path == otherhash(path) == hash(other)id(path) == id(other),其中other是直接从^{中提取的项目。然而,我得到了以下信息

path in thedict:
>> False

并在KeyError中尝试以下结果

thedict[path]

所以我的问题是,在什么情况下这是可能的?我本以为如果pathlist(thedict)中,那么它一定在thedict.keys()中,因此我们必须能够写thedict[path]。这个假设有什么错

进一步资料

如果有帮助,下面列出了相关的课程。正是在{}一级观察到了上述问题

class Path:
    pass

@dataclass
class ConfigurationPath(Path):
    configurationName: str = None
    
    def __repr__(self) -> str:
        return self.configurationName

    def __hash__(self):
        return hash(self.configurationName)

    def __eq__(self, other):
        if not isinstance(other, ConfigurationPath):
            return False
        return self.configurationName == other.configurationName

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

@dataclass
class SpecificationPath(Path):
    configurationPath: ConfigurationPath
    specificationName: str = None
    
    def __repr__(self) -> str:
        return f"{self.configurationPath}.{self.specificationName or ''}"

    def __hash__(self):
        return hash((self.configurationPath, self.specificationName))
    
    def __eq__(self, other):
        if not isinstance(other, SpecificationPath):
            return False
        if self.configurationPath != other.configurationPath:
            return False
        if self.specificationName != other.specificationName:
            return False
        return True

下面是(Spyder)调试终端中的输出,其中pf是一个包含使用路径作为键的paths字典的对象,该对象(self)具有路径

In : others = list(pf.paths.keys())
In : other = others[1]
In : self.path is other
Out[1]: True
In : self.path in pf.paths
Out[1]: False

Tags: pathinselffalsereturnifdefhash
1条回答
网友
1楼 · 发布于 2024-09-28 19:02:36

your comment

The paths do want to be mutable as I am setting specificationName to None in places (leaving them Anonymous to be filled out later). Further, it is on an instance where the specificationName is None that this occurs, however in my simple test scripts I can get away with setting this to None without an error. Could mutability of the hashable instances cause an error such as this?

这是你的问题。您在创建之后立即将这些对象放入dict中,而specificationNameNone,因此它使用基于None的哈希代码存储在dict中(该哈希代码缓存在dict本身中,使用该哈希代码是将来查找对象的唯一方法)。如果随后将其更改为产生不同散列值的任何(读取几乎所有其他内容),则该对象存储在与旧散列代码相对应的bucket中,但使用它进行查找会计算新散列代码,并且找不到该bucket

如果specificationName必须是可变的,那么它不能是散列的一部分,就这么简单。这可能会增加碰撞,但也没办法;一个可变字段不能成为散列的一部分而不触发这个确切的问题

相关问题 更多 >