相互参照的酸洗对象 [英] Pickling objects that refer to each other
问题描述
我有三个Python类,分别为Student
,Event
和StudentEvent
.
I have three Python classes, Student
, Event
, and StudentEvent
.
为简单起见:
class Student:
def __init__(self, id):
self.id = id
class Event:
def __init__(self, id):
self.id = id
self.studentevents = []
class StudentEvent:
def __init__(self, student, event, id):
self.student = student
self.event = event
self.id = id
我每个类都有成千上万个实例,并将这些实例放入字典中以供阅读和分析.读取和创建对象需要花费很多时间,因此我想将它们腌入3个字典中,分别是students_dict
,events_dict
,studentevents_dict
.
I have between thousands and millions of instances of each of these classes, which I put into dictionaries that I can read and analyze. Reading and creating the objects takes a lot of time, so I'd like to pickle them into them into 3 dictionaries, students_dict
, events_dict
, studentevents_dict
.
好的,我可以做到.但是,如果我以后取消对字典的访问,studentevents_dict
中的学生和事件将不会在students_dict
和events_dict
中引用相同的Students
和Events
,对吗?
So, fine, I can do that. But, if I un-pickle the dictionaries at a later date, the students and events in the studentevents_dict
won't refer to the same Students
and Events
in the students_dict
and events_dict
, correct?
如果稍后再修改对象,例如在Event
对象中填充关联的StudentEvents
列表,则可能会出现问题,因为StudentEvent
引用的事件将不是<在events_dict
中具有相同ID的c1>.
If I modify the objects at a later time, for example, populating the list of associated StudentEvents
in the Event
objects, that might be problematic because the event referenced by the StudentEvent
won't be the Event
with the same id in the events_dict
.
推荐答案
正确.如果需要保留对象之间的指针关系,则必须在一个元组中将它们腌制在一起.在这里,我使用的是dill
而不是pickle
,但是效果应该是相同的.这适用于类实例(如图所示),字典或其他方式.
Correct. If you need to preserve the pointer relationship between the objects, you have to pickle them together in a tuple for example. Here I'm using dill
instead of pickle
, but the effect should be the same. This works for class instances (as shown), dicts, or otherwise.
>>> class A:
... def __init__(self, b):
... self.b = b
...
>>> class B:
... pass
...
>>> import dill
>>>
>>> b = B()
>>> a = A(b)
>>>
>>> f = open('_sed', 'wb')
>>> dill.dump(({1:a},{2:b}), f)
>>> f.close()
然后再……
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> f = open('_sed', 'rb')
>>> t = dill.load(f)
>>> f.close()
>>> t
({1: <__main__.A instance at 0x10906a440>}, {2: <__main__.B instance at 0x10906a830>})
>>> t[0][1].b
<__main__.B instance at 0x10906a830>
这篇关于相互参照的酸洗对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!