Pickle all attributes except one

后端 未结 6 976
野性不改
野性不改 2021-01-17 07:51

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 wi

6条回答
  •  没有蜡笔的小新
    2021-01-17 08:10

    Using is_instance_method from an earlier answer:

    def __getstate__(self):
        return dict((k, v) for k, v in self.__dict__.iteritems()
                           if not is_instance_method(getattr(self, k)))
    

    Although the is_instance_method operation can also be performed less "magically" by taking an known instance method, say my_func, and taking its type.

    def __getstate__(self):
        instancemethod = type(self.my_func)
        return dict((k, v) for k, v in self.__dict__.iteritems()
                           if not isinstance(getattr(self, k), instancemethod))
    

提交回复
热议问题