如何恢复腌制的类及其实例 [英] How to recover a pickled class and its instances

查看:98
本文介绍了如何恢复腌制的类及其实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想存储一个类和许多实例供以后使用,或提供给其他人.

I would like to store a class and many instances for later use, or to give to someone else.

到目前为止,我可以腌制和恢复实例,但是在加载它们之前,我必须手动重新创建类.

So far I can pickle and recover the instances, but I have to recreate the class by hand before loading them.

我查看了文档使我相信我应该能够以某种方式执行此操作,但是我似乎无法确切地找到执行该操作的方法.

I've looked at this documentation which leads me to believe I should be able to do this somehow, but I can't seem to find out exactly how to do it.

我已阅读此答案讨论了dill的用法(请参阅

I've read this answer discussing the use of dill(see this answer also), but I don't have dill installed. I'd like a pickle solution if it exists.

import numpy as np
import pickle

class wow(object):
    def __init__(self, x):
        self.x = x

w5 = wow(np.arange(5))
w3 = wow(range(3))

with open("w5w3.pickle", "w") as outfile:
    pickle.dump([w5, w3], outfile)

# save the class also
with open("wow.pickle", "w") as outfile:
    pickle.dump(wow, outfile)

# OK, now delete class wow, then try to recover the pickles
del wow, w3, w5

try:
    with open("wow.pickle", "r") as infile:
        wow = pickle.load(infile)

except Exception, e:  # returns: "'module' object has no attribute 'wow'"
    print str(e)
    print "so manually recreate class wow"

    class wow(object):
        def __init__(self, x):
            self.x = x  

with open("w5w3.pickle", "r") as infile:
    W = pickle.load(infile)

for thing in W:
    print type(thing.x), thing.x

推荐答案

我认为该错误是由于删除了类定义而引起的.使用Python(据我所知也是Java)进行对象序列化需要在其中定义类.

I believe the error is caused because you deleted the class definition. Object serialization in Python (which to my knowledge is also in Java) requires the class definition to be there.

从链接的文档中

请注意,函数(内置的和用户定义的)是通过完全限定"的名称引用而不是值进行酸洗的.这意味着仅对函数名称以及定义该函数的模块的名称进行了腌制.既不对函数的代码,也不对其任何函数属性进行腌制.因此,定义模块必须在拆解环境中是可导入的,并且该模块必须包含命名对象,否则将引发异常. [4]

Note that functions (built-in and user-defined) are pickled by "fully qualified" name reference, not by value. This means that only the function name is pickled, along with the name of the module the function is defined in. Neither the function’s code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised. [4]

类似地,通过命名引用对类进行酸洗,因此在未酸洗环境中适用相同的限制.请注意,该课程的任何代码或数据都不会被腌制

Similarly, classes are pickled by named reference, so the same restrictions in the unpickling environment apply. Note that none of the class’s code or data is pickled

如果要向朋友发送类和实例,请通过定义类wow的代码发送类,并通过pickle文件发送实例.

If you want to send your friend the class and instances, send the class through a code defining the class wow, and the instances through the pickle file.

这篇关于如何恢复腌制的类及其实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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