Python pickle:pickle 对象不等于源对象 [英] Python pickle: pickled objects are not equal to source objects

查看:71
本文介绍了Python pickle:pickle 对象不等于源对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这是预期的行为,但我想检查一下并找出原因,因为我所做的研究是空白的

我有一个函数可以提取数据,创建自定义类的新实例,然后将其附加到列表中.该类只包含变量.

然后我将该列表使用协议 2 作为二进制文件腌制到一个文件中,稍后我重新运行脚本,从我的源中重新提取数据,我有一个包含自定义类实例的新列表,用于测试我保留data 与源数据相同.

重新加载pickle文件

现在当我做一个:

print source_list == pickle_list

这总是返回False,我不知道为什么,如果我打印列表或查看结构,它们看起来完全一样.

任何想法都很棒,这是我需要整理的最后一点.

解决方案

比较同一个类的两个对象默认会产生 False(除非它们是同一个对象),即使它们的内容相同;换句话说,默认情况下,来自同一类的两个直观相同"的对象被认为是不同的.下面是一个例子:

<预><代码>>>>C类(对象):... def __init__(self, value):... self.value = 价值...>>>>>>C(12) == C(12)错误的

您想在自定义类中定义 __eq__()(和 __ne__()),以便它为包含相同数据的对象生成 True.更多信息可以在官方文档中找到.对于上面的示例,这将是:

<预><代码>>>>C类(对象):... # ...... def __eq__(self, other):...返回 self.value == other.value... def __ne__(self, other):... return not self == other # 比 self.value 更通用 != other.value...>>>C(12) == C(12) # __eq__() 被调用真的>>>C(12) != C(12) # __ne__() 被调用错误的

I think this is expected behaviour but want to check and maybe find out why, as the research I have done has come up blank

I have a function that pulls data, creates a new instance of my custom class, then appends it to a list. The class just contains variables.

I then pickle that list to a file using protocol 2 as binary, later I re-run the script, re-pull the data from my source, I have a new list with my custom class instances, for testing I keep the data the source data the same.

Reload the pickle file

Now when I do a:

print source_list == pickle_list

this always comes back False, and I have no idea why, if I print the lists or look at the structure they look exactly the same.

Any ideas would be brill, this is my last little bit I need to sort.

解决方案

Comparing two objects of the same class yields False by default (unless they are the same single object), even if they have the same contents; in other words, two intuitively "identical" objects from the same class are considered different, by default. Here is an example:

>>> class C(object):
...     def __init__(self, value):
...         self.value = value
...         
>>> 
>>> C(12) == C(12)
False

You want to define __eq__() (and __ne__()) in your custom class so that it yields True for objects that contain the same data. More information can be found in the official documentation. For the above example, this would be:

>>> class C(object):
...     # ...
...     def __eq__(self, other):
...         return self.value == other.value
...     def __ne__(self, other):
...         return not self == other  # More general than self.value != other.value
...     
>>> C(12) == C(12)  # __eq__() is called
True
>>> C(12) != C(12)  # __ne__() is called
False

这篇关于Python pickle:pickle 对象不等于源对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆