如何 pickle class 定义?

How can I pickle a class definition?

我在酸洗 class 从另一个模块导入 class 时遇到问题。

Immagine 我有一个文件 classA.py 定义了一个 class A:

class A:
    def execute(self):
        print('Hello from class A!')

那我还有一个文件classB.py:

import dill
import classA

class B:
    def __init__(self):
        self.a = classA.A()

    def execute(self):
        self.a.execute()
        print('Hello from class B!')


b = B()

with open('/file/path', 'wb') as f:
    dill.dump(b, f)

如果那么我尝试从不同的目录中解开创建的文件:

with open('file/path', 'rb') as f:
    b = dill.load(f)

我收到错误:

ModuleNotFoundError: No module named 'classB'

它当然可以在我有文件 classA.py 和 classB.py 的同一个文件夹中工作,因为解释器可以找到两个 classes 的定义。

所以我想我必须以某种方式将 classes 的定义带入 pickle 文件中。我该怎么做?

谢谢 斯特凡诺

It works of course in the same folder in which I have the files classA.py and classB.py because the interpreter can find the definition of the two classes. So I guess I have to somehow bring the definition of the classes into the pickle file. How can I do that?

事情不是这样的。您不需要 "bring the definition of the classes into the pickle file" - which would make no sense 因为只有 class 限定名称被腌制 (qualified name => packagename.modulename.classname)

相反,您必须确保定义 classes 的模块在解包时是可导入的 - "importable" 意味着包或模块的父文件夹路径在您的 sys.path.你可以通过几种方式做到这一点(使用 PYTHONPATH 环境变量,直接在你的代码中弄乱 sys.path - 这通常是一个坏主意,有时是正确的解决方案 - 在 vi​​rtualenv 中安装你的模块并激活这个 virtualenv,等等)

注意:当前工作目录始终在您的 sys.path 中排在第一位,这就是 "It works of course in the same folder".

的原因