首页 > 解决方案 > 如何修复 _pickle.PicklingError: can'tpickle : 它不是同一个对象

问题描述

我正在动态生成一些类(附加代码),现在需要腌制它们。但是,我得到 can't pickle 错误,说它不是同一个对象。

import pickle


class TagBase:
    pass


class Tags:
    container_tmi = "container"
    pass

taglist = [attr for attr in dir(Tags) if not callable(
    getattr(Tags, attr)) and not attr.startswith("__")]

for _ in taglist:
    taginfo = getattr(Tags, _)
    globals()[taginfo] = type(taginfo, (TagBase,), {})()

    
def launcher():
    l = [container]
    with open("l.pickle", "wb") as fh:
        pickle.dump(l, fh)

launcher()

作为一种解决方法,我可能只是编写一个 scipt 来生成类定义而不是动态创建它们,但仍然想知道为什么会出现此错误以及任何可能的修复。

标签: pythonpickledynamic-class-creation

解决方案


推荐阅读