gpt4 book ai didi

python - 如何让 python 数据类继承 __hash__?

转载 作者:行者123 更新时间:2023-12-01 16:03:22 29 4
gpt4 key购买 nike

以下将起作用,但我宁愿不需要重复 __hash__在每个子类中。有没有办法告诉数据类继承哈希函数(即不将其设置为 None )?

from dataclasses import dataclass


@dataclass
class Hashable:

def __hash__(self):
hashed = hash((
getattr(self, key)
for key in self.__annotations__
))
return hashed


@dataclass
class Node(Hashable):
name: str = 'Undefined'

def __hash__(self):
return Hashable.__hash__(self)

最佳答案

你的原因__hash__正在设置为 Nonedataclasses试图阻止你用脚射击自己。你的第二堂课有 eq=True用于数据类装饰器(这是默认值)。从文档:

Here are the rules governing implicit creation of a __hash__() method. Note that you cannot both have an explicit __hash__() method in your dataclass and set unsafe_hash=True; this will result in a TypeError.

If eq and frozen are both true, by default dataclass() will generate a __hash__() method for you. If eq is true and frozen is false, __hash__() will be set to None, marking it unhashable (which it is, since it is mutable). If eq is false, __hash__() will be left untouched meaning the __hash__() method of the superclass will be used (if the superclass is object, this means it will fall back to id-based hashing).



所以只要通过 eq=False :
In [1]: from dataclasses import dataclass
...:
...:
...: @dataclass
...: class Hashable:
...:
...: def __hash__(self):
...: hashed = hash((
...: getattr(self, key)
...: for key in self.__annotations__
...: ))
...: return hashed
...:
...:
...: @dataclass(eq=False)
...: class Node(Hashable):
...: name: str = 'Undefined'
...:

In [2]: hash(Node())
Out[2]: -9223372036579626267

但是,正如评论中指出的那样,这不是很安全,因为您有一个可变对象,现在可以进行哈希处理,并且与 __eq__ 的实现不一致。 ,它继承自 Hashable

关于python - 如何让 python 数据类继承 __hash__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53990296/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com