这是腌制实例方法的正确方法吗?如果是,为什么在Python 3中不呢? [英] Is this the right way to pickle instance methods? If yes, why isn't it in Python 3?

查看:95
本文介绍了这是腌制实例方法的正确方法吗?如果是,为什么在Python 3中不呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实例方法不能同时在Python 2或Python 3中被腌制.

Instance methods can not automatically be pickled in both Python 2 or Python 3.

我需要使用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

另请参阅相关内容: https://stackoverflow.com/a/21345273/2379433

这篇关于这是腌制实例方法的正确方法吗?如果是,为什么在Python 3中不呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆