gpt4 book ai didi

python - 如何在 Python 中创建 pickle-friend 对象 ID?

转载 作者:行者123 更新时间:2023-11-28 16:39:59 26 4
gpt4 key购买 nike

我正在尝试使用 Python pickle 模块来持久化一些 Python 对象,这些对象使用

id(object)

作为他们的外部标识符(例如,在网页上)。

问题是,我发现在 pickle dump/load cycle 之后,id(object) 值发生了变化。这使得 id(object) 无法用于需要不变值的外部标识符。

那么如何方便地创建一个 idpickle/unpickle 之后不会改变?

最佳答案

你不能。

id 的文档:

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime.

所以两个不同的对象(即如果 a is not b is True)有两个不同的 id。

备选方案:

(1) 如果你的类型是可哈希的,你可以使用hash:

hash((1,2,3))

(2) 只有少数东西是可散列的,但是你可以散列 pickle ,例如

hash(pickle.dumps([1,2,3]))

(3) 您可以为每个对象显式设置一个 id 属性。

关于python - 如何在 Python 中创建 pickle-friend 对象 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20627612/

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