Skip to main content
 首页 » 编程设计

python之与 __init__.py 混淆并从子模块导入父模块中的类

2025年05月04日10dudu

我有点难以理解如何从子模块中导入父模块中的类。我有以下目录结构:

   module/ 
      __init__.py        (1) 
      common.py          (containing testfunc and CommonClass) 
      submod/ 
         __init__.py     (2) 
         test.py         (containing TestClass) 

在 (1) 我有:

   from common import * 

所以我可以直接做:

   import module 
   module.testfunc() 

在 (2) 我有:

   from test import TestClass 

所以在 module 中我可以做:

   import submod 
   class_inst = submod.TestClass() 

现在在 TestClass(包含在 test.py 中)我想使用 CommonClass 的一个实例,所以我首先尝试导入它使用:

   from ..common import * 

效果很好,但是当我尝试在 TestClass 中创建 CommonClass 的实例时:

   class TestClass(object): 
       def __init__(self): 
           self.inst = CommonClass() 

我得到错误:

   NameError: global name 'CommonClass' is not defined 

同样,如果我改为尝试 from ..common import CommonClass,我会得到错误:

   ImportError: cannot import name CommonClass 

据我所知,CommonClass 应该在 test.py 中可见,所以我不确定为什么找不到它。我感觉我对 __init__.py 的用法有些不理解。是否有人可以通过指出我犯的任何明显错误来提供帮助?

请您参考如下方法:

我想说“循环导入”,但我不能完全准确地指出它。您看到的 ImportError 很可能就是一个症状。通常,如果您导入一个模块,而该模块又导入其他东西,并且导入链最终导入了启动所有导入的模块,您将得到一个 ImportError。

你能否将 CommonClass 移动到一个新模块 module.submod.utils 中,它不会从你的代码中导入任何其他内容,然后从那里导入它?