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

Why does a pickle loaded after saving differs from the original object?

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

我已经尝试只使用初始化函数中定义的实例属性,而不使用 class 属性,但错误仍然存​​在。

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。

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

您可以在 Person class 上显式声明 __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)

现在您的比较将 return 符合预期。

运行 您的代码并打印 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)