当该对象通过其属性之一引用自身时,从具有插槽的类中提取对象的正确方法是什么?这是一个简单的示例,使用我当前的实现,我不确定它是否 100% 正确:
import weakref
import pickle
class my_class(object):
__slots__ = ('an_int', 'ref_to_self', '__weakref__')
def __init__(self):
self.an_int = 42
self.ref_to_self = weakref.WeakKeyDictionary({self: 1})
# How to best write __getstate__ and __setstate__?
def __getstate__(self):
obj_slot_values = dict((k, getattr(self, k)) for k in self.__slots__)
# Conversion to a usual dictionary:
obj_slot_values['ref_to_self'] = dict(obj_slot_values['ref_to_self'])
# Unpicklable weakref object:
del obj_slot_values['__weakref__']
return obj_slot_values
def __setstate__(self, data_dict):
# print data_dict
for (name, value) in data_dict.iteritems():
setattr(self, name, value)
# Conversion of the dict back to a WeakKeyDictionary:
self.ref_to_self = weakref.WeakKeyDictionary(
self.ref_to_self.iteritems())
例如,这可以通过以下方式进行测试:
def test_pickling(obj):
"Pickles obj and unpickles it. Returns the unpickled object"
obj_pickled = pickle.dumps(obj)
obj_unpickled = pickle.loads(obj_pickled)
# Self-references should be kept:
print "OK?", obj_unpickled == obj_unpickled.ref_to_self.keys()[0]
print "OK?", isinstance(obj_unpickled.ref_to_self,
weakref.WeakKeyDictionary)
return obj_unpickled
if __name__ == '__main__':
obj = my_class()
obj_unpickled = test_pickling(obj)
obj_unpickled2 = test_pickling(obj_unpickled)
这是一个正确/可靠的实现吗?如果从一个类继承,__getstate__
应该如何__setstate__
写?由于“循环”字典,内部是否存在内存泄漏?my_class
__slots__
__setstate__
PEP 307中有一句话让我想知道酸洗my_class
对象是否可能以一种健壮的方式进行:
该
__getstate__
方法应该返回一个表示对象状态的可挑选值,而不引用对象本身。
这是否与对对象本身的引用被腌制的事实相冲突?
这是很多问题:任何评论、评论或建议将不胜感激!