我想存储一个类和许多实例以备后用,或提供给其他人。
到目前为止,我可以 pickle 和恢复实例,但我必须在加载它们之前手动重新创建类。
我看过this文档让我相信我应该能够以某种方式做到这一点,但我似乎无法找到确切的方法。
编辑:我读过这个answer讨论 dill
的使用(另见 this 回答),但我没有安装 dill
。如果有 pickle 解决方案,我想要。
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 中也是如此)需要类定义。
来自您的链接文档:
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
如果您想向 friend 发送类和实例,请通过定义类 wow
的代码发送类,并通过 pickle 文件发送实例。
关于python - 如何恢复 pickle 类及其实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34261379/