腌制除一个以外的所有属性 [英] Pickle all attributes except one
问题描述
编写__getstate__
方法来腌制几乎所有对象的属性,但排除其中一些属性的最佳方法是什么?
What is the best way to write a __getstate__
method that pickles almost all of an object's attributes, but excludes a few?
我有一个具有许多属性的对象,包括一个引用实例方法的对象.实例方法不可腌制,因此在尝试腌制该对象时出现错误:
I have an object with many properties, including one that references an instancemethod. instancemethod's are not pickleable, so I'm getting an error when I try to pickle this object:
class Foo(object):
def __init__(self):
self.a = 'spam'
self.b = 'eggs'
self.c = 42
self.fn = self.my_func
def my_func(self):
print 'My hovercraft is full of eels'
import pickle
pickle.dumps(Foo()) # throws a "can't pickle instancemethod objects" TypeError
此__getstate__
方法可解决此问题,但随后我必须手动包含要序列化的所有属性:
This __getstate__
method fixes this, but then I have to manually include all the properties I want to serialize:
def __getstate__(self):
return { 'a': self.a, 'b': self.b, 'c': self.c }
如果我的对象具有许多属性或经常更改,那么扩展性或维护性就不太好.
That's not very scalable or maintainable if I have an object with many attributes or that changes frequently.
我能想到的唯一替代方法是某种辅助函数,该函数会根据对象的类型迭代对象的属性并将其添加(或不添加)到字典中.
The only alternative I can think of is some kind of helper function that iterates through an object's properties and adds them (or not) to the dictionary, based on the type.
推荐答案
我能想到的唯一替代方法是某种辅助函数,该函数会根据对象的类型迭代对象的属性并将其添加(或不添加)到字典中.
The only alternative I can think of is some kind of helper function that iterates through an object's properties and adds them (or not) to the dictionary, based on the type.
是的,如果您想要足够的魔术"来让自己变得懒惰(和/或允许动态添加属性),那么我想剩下的几乎就是剩下的了.请记住,"pickle
无法处理此问题"不是您可能不想在腌制状态下包含某些东西的唯一原因.
Yeah, I think that's pretty much what you're left with, if you want enough "magic" to allow yourself to be lazy (and/or allow for dynamically added attributes). Keep in mind that "pickle
can't handle this" isn't the only reason you might not want to include something in the pickled state.
但是,假设您具有我应该对此腌制?"的代码,这并不像您想的那么难.逻辑:
But it's not as hard as you seem to think, assuming you have code for the "should I pickle this?" logic:
def __getstate__(self):
return dict((k, v) for (k, v) in self.__dict__.iteritems() if should_pickle(v))
这篇关于腌制除一个以外的所有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!