具有对象值的 Pickle 字典反序列化为不同的值

Pickle dictionary with object value deserialises with different value

我有一本字典,其中一个值是一个对象。我正在尝试使用 Pickle 模块序列化和反序列化这本字典,如下所示:

import pickle

class ExampleClass(object):
    def __init__(self, obj_id, name, type):
        self.obj_id = obj_id
        self.name = name
        self.type = type

my_obj = ExampleClass(1, 'tu42', 'bas5')

example_dict = {'object': my_obj,
                 'date': '02041980',
                 'event': 'test'}

with open("test.pickle", "wb") as handle:
    pickle.dump(example_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)

with open("test.pickle", "rb") as handle:
    reconstituted = pickle.load(handle)

print(example_dict)
print(reconstituted)
print(example_dict == reconstituted) # expected to be True

这给出了以下输出:

{'object': <__main__.ExampleClass object at 0x000001D726852148>, 'date': '02041980', 'event': 'test'}
{'object': <__main__.ExampleClass object at 0x000001D7268527C8>, 'date': '02041980', 'event': 'test'}
False

字典的对象值 'object': my_obj 不同,我不明白为什么会这样。

任何使这个 example_dict pickle 与其相应的重构值相同的建议或信息都将非常有用。

@Straw 的评论指出了正确的方向。

如果其他人可能发现自己处于类似情况,则需要根据对象实例的属性比较对象实例是否相等 as described here

对于本文中的示例,实施 __eq__ 方法将允许比较对象实例:

import pickle
class ExampleClass(object):
    def __init__(self, obj_id, name, type):
        self.obj_id = obj_id
        self.name = name
        self.type = type

    def __eq__(self, other):
        if not isinstance(other, ExampleClass):
            return NotImplemented

        return self.obj_id == other.obj_id and self.name == other.name and self.type == other.type

my_obj = ExampleClass(1, 'tu42', 'bas5')

example_dict = {'object': my_obj,
                 'date': '02041980',
                 'event': 'test'}

with open("test.pickle", "wb") as handle:
    pickle.dump(example_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)

with open("test.pickle", "rb") as handle:
    reconstituted = pickle.load(handle)

print(example_dict)
print(reconstituted)
print(example_dict == reconstituted)

现在 return True