这是腌制实例方法的正确方法吗?如果是,为什么在Python 3中不呢?
实例方法不能同时在Python 2或Python 3中被腌制.
Instance methods can not automatically be pickled in both Python 2 or Python 3.
I need to pickle instance methods with Python 3 and I ported example code of Steven Bethard to Python 3:
import copyreg
import types
def _pickle_method(method):
func_name = method.__func__.__name__
obj = method.__self__
cls = method.__self__.__class__
return _unpickle_method, (func_name, obj, cls)
def _unpickle_method(func_name, obj, cls):
for cls in cls.mro():
try:
func = cls.__dict__[func_name]
except KeyError:
pass
else:
break
return func.__get__(obj, cls)
copyreg.pickle(types.MethodType, _pickle_method, _unpickle_method)
此方法对于酸洗实例方法是不可靠的证明吗?还是有些事情会严重出错?我已经通过一些模拟类对其进行了测试,一切似乎都可以正常工作.
Is this method fool proof for pickling instance methods? Or can some things go horribly wrong? I have tested it with some mock up classes and everything seem to work.
如果什么都不会出错,为什么在Python 3中无法使用标准的pickle实例方法?
If nothing can go wrong, why isn't it possible in Python 3 to standard pickle instance methods?
如果要腌制类实例(和实例方法),只需使用dill
...
If you want to pickle class instances (and instance methods), just use dill
...
>>> import dill
>>>
>>> class Foo:
... def bar(self, x):
... return self.y + x
... def zap(self, y):
... self.y = y
... y = 1
...
>>> f = Foo()
>>> f.zap(4)
>>> f.monty = 'python'
>>>
>>> _f = dill.dumps(f)
>>> del Foo
>>> del f
>>> f = dill.loads(_f)
>>> f.monty
'python'
>>> f.y
4
>>>
>>> _b = dill.dumps(f.bar)
>>> del f
>>> bar = dill.loads(_b)
>>> bar(4)
8
>>>
如上所示,
dill
在删除类对象时有效...因此,如果在未定义类的情况下启动全新的python会话,或者更改了类定义,则也可以使用. dill
甚至在您没有类对象的实例或可用的类实例时也可以使用.如果要查看操作方法,请查看dill
源代码: https://github.com /uqfoundation/dill
dill
works when you delete the class object, as seen above… so it also works if you start a fresh python session without the class defined, or if you change the class definition. dill
even works when you don't have an instance of the class object, or a class instance available. If you want to see how to do it, look at the dill
source code: https://github.com/uqfoundation/dill