gpt4 book ai didi

python - 散列 Python 类是个好主意吗?

转载 作者:太空狗 更新时间:2023-10-30 00:28:53 27 4
gpt4 key购买 nike

例如,假设我这样做:

>>> class foo(object):
... pass
...
>>> class bar(foo):
... pass
...
>>> some_dict = { foo : 'foo',
... bar : 'bar'}
>>>
>>> some_dict[bar]
'bar'
>>> some_dict[foo]
'foo'
>>> hash(bar)
165007700
>>> id(bar)
165007700

基于此,该类似乎被散列为它的 ID 号。因此,不应该担心将 bar 散列为 foobar 或更改散列值的任何危险如果我改变类。

这种行为是否可靠,或者这里有什么问题吗?

最佳答案

是的,任何未实现 __hash__() 函数的对象都将在散列时返回其 id。来自 Python Language Reference: Data Model - Basic Customization :

User-defined classes have __cmp__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns id(x).

但是,如果您希望拥有唯一标识符,请使用 id 来明确您的意图。对象的散列应该是其组件散列的组合。有关详细信息,请参阅上面的链接。

关于python - 散列 Python 类是个好主意吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1335556/

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