如何阻止在Python中腌制属性 [英] How to stop attributes from being pickled in Python
问题描述
我正在使用gnosis.xml.pickle将我自己的类的对象转换为xml.初始化该对象,以便:
I am using gnosis.xml.pickle to convert an object of my own class to xml. The object is initialized so that:
self.logger = MyLogger()
但是当我确实将对象转储到字符串中时,我得到了一个异常,指出该选择器遇到了无法修复的类型(thread.lock).
But when I do dump the object to a string I get an exception stating that the pickler encountered an unpickleable type (thread.lock).
有没有一种方法可以标记"记录器属性,以便选择器知道不尝试对它进行标记?
Is there a way to 'tag' the logger attribute so that pickler will know not to try and pickle that attribute?
推荐答案
您可以为类定义两个方法__getstate__
和__setstate__
,以覆盖默认的酸洗行为.
You can define two methods, __getstate__
and __setstate__
, to your class to override the default pickling behavior.
http://docs.python.org/library/pickle.html#object.__getstate__
__getstate__
应该返回您要腌制的属性的字典.
__getstate__
should return a dict of attributes that you want to pickle.
def __getstate__(self):
d = dict(self.__dict__)
del d['logger']
return d
__setstate__
应该使用提供的字典设置对象.
__setstate__
should setup your object with the provided dict.
def __setstate__(self, d):
self.__dict__.update(d) # I *think* this is a safe way to do it
请注意,解开时不会调用__init__
,因此您必须在__setstate__
Note that __init__
won't be called when unpickling so you'll have to create your logger in __setstate__
这篇关于如何阻止在Python中腌制属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!