You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Colab导入自定义Python类遇ImportError问题求助

问题排查与解决方案

错误原因

你的NewClassMethod类定义在filedir1/filedir2/new_class.py文件中,但该目录下的__init__.py为空。Python导入包时会优先读取__init__.py的导出内容,由于文件中没有暴露NewClassMethod,直接从包导入自然找不到该类。

解决办法

办法一:直接从模块导入

修改导入语句,指定具体模块:

from filedir1.filedir2.new_class import NewClassMethod

办法二:修改__init__.py暴露类

打开/content/drive/MyDrive/filedir1/filedir2/__init__.py,添加以下代码:

from .new_class import NewClassMethod

保存后,即可继续使用原来的导入语句:

from filedir1.filedir2 import NewClassMethod

额外检查项

  • 确认new_class.py确实位于filedir1/filedir2目录下,路径无错误
  • 检查new_class.py中类名拼写是否为NewClassMethod,大小写和符号完全匹配
  • 若在Colab挂载的Drive中修改了文件,建议重启运行时,避免旧缓存导致的导入异常

内容的提问来源于stack exchange,提问作者geo derek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:41:05