pickle无法序列化动态创建的class,要怎么做才能存储动态创建的类?
import pickle
class B:
a = 1
b = 2
c = 3
my = []
def you():
with open("you.pkl", "wb") as f:
pickle.dump(B, f)
def my():
conf_txt = """
class A:
a = 1
b = 2
c = 3
my = []
"""
glob, loc = {}, {}
exec(conf_txt, glob, loc)
with open("conf.pkl", "wb") as f: # 'loc': {'A': <class 'A'>}
# error, _pickle.PicklingError: Can't pickle <class 'A'>: attribute lookup A on builtins failed
pickle.dump(loc["A"], f)
def that():
C = type("C", (B, ), {"hello":"tom"})
print("hello:", C.hello)
with open("c.pkl", "wb") as f:
# _pickle.PicklingError: Can't pickle <class '__main__.C'>: attribute lookup C on __main__ failed
pickle.dump(C, f)
if __name__ == "__main__":
you() # it works
my() # 有问题
# that() # 有问题
对于my()、that(),一个是从conf.txt里加载信息,exec后将配置类保存但是失败。另一个通过type动态创建class,pickle序列化还是失败。我应该怎么做才能序列化动态类?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我只见过你这样写类:文字转类,换一种编码方式