保存后加载的泡菜为什么与原始对象不同?

时间:2019-08-20 14:25:52

标签: python pickle

我使用泡菜来保存对象列表。用泡菜保存列表并再次加载此相同列表后,我将新加载的列表与原始列表进行比较。奇怪的是,这两个对象不同。为什么会这样呢?不应该一样吗?

我已经尝试仅使用init函数中定义的实例属性,而没有类属性,但错误仍然存​​在。

import pickle as p

class Person(object):
    def __init__(self, name=None, job=None, quote=None):
        self.name = name
        self.job = job
        self.quote = quote


personList = [Person("Payne N. Diaz", "coach", "Without exception, there is no rule!"),
              Person("Mia Serts", "bicyclist", "If the world didn't suck, we'd all fall off!"),
              Person("Don B. Sanosi", "teacher", "Work real hard while you wait and good things will come to you!")]

with open('test_list.p', 'wb') as handle:
    p.dump(personList, handle, protocol=p.HIGHEST_PROTOCOL)

with open('test_list.p', 'rb') as handle:
    personList2 = p.load(handle)

print(personList == personList2)

我希望True将被打印出来,但打印结果为False。

2 个答案:

答案 0 :(得分:4)

您尚未定义比较Person对象的显式方法。因此,Python可以比较它们的唯一方法是通过它们的ID(即它们的内存地址)。从泡菜中装载的物品的地址与原始地址不同-因为它们是新对象,所以必须与原始地址不同-因此列表将不会比较相等。

您可以在Person类上声明一个显式__eq__方法:

class Person(object):
    def __init__(self, name=None, job=None, quote=None):
        self.name = name
        self.job = job
        self.quote = quote

    def __eq__(self, other):
        return (self.name == other.name and self.job == other.job and self.quote == other.quote)

现在您的比较将按预期返回True。

答案 1 :(得分:1)

运行代码并打印personList1和personList2;看来您正在检查对象是否相同,而不是内容是否相同。

False
[<__main__.Person object at 0x000001A8EAA264A8>, <__main__.Person object at 0x000001A8EAA26A20>, <__main__.Person object at 0x000001A8EAA26F98>]
[<__main__.Person object at 0x000001A8EAA26240>, <__main__.Person object at 0x000001A8EAA260F0>, <__main__.Person object at 0x000001A8EAA26908>]

如果将print语句更改为以下内容,则它将产生true,因为它正在检查内容。

print(personList[0].name == personList2[0].name)