【发布时间】:2019-03-04 10:09:18
【问题描述】:
我需要腌制一个我已实例化的 python 类,因此需要使用相对路径。我正在使用 Python 版本 3.6.6。以下是项目结构和代码的示例:
modelling/
test.py
mod1/
__init__.py
classic_mod.py
初始化.py
from .classic_mod import classic
classic_mod.py
class classic:
def __init__(self, input_string):
self.input_string = input_string
print(self.input_string)
def log_info(self):
print(self.input_string)
test.py
from .mod1 import classic_mod
from sklearn.externals import joblib
model = classic_mod.classic("Hello World!")
joblib.dump(model, "model.pkl")
如果我使用绝对路径,当我将 pickle 文件加载到另一个文件夹中的 python 时会出现问题。当我运行 test.py 时,我收到一条错误消息:
Traceback (most recent call last):
File "test.py", line 2, in <module>
from .mod1 import classic_mod
ModuleNotFoundError: No module named '__main__.mod1'; '__main__' is not a package
我怎样才能解决这个导入错误,同时腌制这个类,以便我可以在其他地方使用?
【问题讨论】:
-
你的类名最好以大写字母开头。
-
from .mod1 import classic_mod,mod1是模块所以不合适,使用from mod1 import classic_mod
标签: python python-3.x scikit-learn pickle