gpt4 book ai didi

python - 动态类定义的 pickle

转载 作者:太空宇宙 更新时间:2023-11-03 14:23:22 25 4
gpt4 key购买 nike

我正在尝试将动态生成的类 pickle 为替代类的工厂。类似于以下内容:

import sys, pickle

class BC(object):
pass

C = type("NewClassName", (BC,), {})

pickle.dump(C, sys.stdout)

这会导致以下错误:

pickle.PicklingError: Can't pickle <class '__main__.NewClassName'>: it's not found as __main__.NewClassName

对于动态生成的类的对象,您可以定义一个 __reduce__ 方法,但是有没有办法只为类定义实现这一点。

我不想直接使用 BC,因为我只需要它作为新类的工厂。

最佳答案

一个简单的错误解决方法是使用类名作为变量名,以便 pickle 可以找到它:

import sys, pickle

class BC(object):
pass

<strong>NewClassName</strong> = type("NewClassName", (BC,), {})

pickle.dump(<strong>NewClassName</strong>, sys.stdout)

但是,这可能并不能真正满足您的需求。加载 pickled 类时:

pickle.loads("""c__main__
NewClassName
p0
.""")

你再次得到错误:

AttributeError: 'module' object has no attribute 'NewClassName'

除非您已经定义了类。


作为documentation状态:

pickle can save and restore class instances transparently, however the class definition must be importable and live in the same module as when the object was stored.

所以你不能用它来生成新的类,只是为了确保你的对象引用正确的类。


有一些变通方法,如 pickling type 参数,如 other answer 中所示,但即便如此,如果不在 pickling 和 unpickling 过程的全局命名空间中公开类,你将无法 pickle objects (即 __main__.ClassName 必须引用类)。

因此,我会重新考虑整个动态类方法。

关于python - 动态类定义的 pickle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24364408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com