pickle无法序列化动态创建的class,要怎么做才能存储动态创建的类?
import pickleclass 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序列化还是失败。我应该怎么做才能序列化动态类?
回答:
我只见过你这样写类:文字转类,换一种编码方式
以上是 pickle无法序列化动态创建的class,要怎么做才能存储动态创建的类? 的全部内容, 来源链接: utcz.com/p/937992.html