简体   繁体   English

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

[英]Confusion with __init__.py and importing classes in parent module from submodule

I'm having a little difficulty understanding how to import classes from a parent module from within a submodule. 我在理解如何从子模块中从父模块导入类时遇到了一些困难。 I have the following directory structure: 我有以下目录结构:

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

in (1) I have: (1)我有:

   from common import *

So I can do directly: 所以我可以直接做:

   import module
   module.testfunc()

in (2) I have: (2)我有:

   from test import TestClass

So from within module I can do: 因此,在module内,我可以执行以下操作:

   import submod
   class_inst = submod.TestClass()

Now in TestClass (contained in test.py ) I want to use an instance of CommonClass , so I tried first importing it using: 现在在TestClass (包含在test.py ),我想使用CommonClass的实例,因此我尝试首先使用以下方式导入它:

   from ..common import *

Which works fine, but when I try to create an instance of CommonClass in TestClass : 效果很好,但是当我尝试在TestClass创建CommonClass的实例时:

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

I get the error: 我得到错误:

   NameError: global name 'CommonClass' is not defined

Similarly if I try instead from ..common import CommonClass I get the error: 同样,如果我尝试from ..common import CommonClass尝试from ..common import CommonClass收到错误消息:

   ImportError: cannot import name CommonClass

As far as I can tell, CommonClass should be visible from within test.py , so I'm not sure why it can't be found. 据我所知, CommonClass应该在test.py可见,所以我不确定为什么找不到它。 I have a feeling there is something I'm not understanding about the usage of __init__.py . 我有一种关于__init__.py的用法我不了解的感觉。 Is there anyone who can help by pointing out any obvious mistakes I am making? 有没有人可以指出我犯的明显错误来提供帮助?

I'd like to say "circular imports" but I can't quite pinpoint it. 我想说“圆形进口”,但我不能说清楚。 The ImportError you're seeing might well be a symptom of that. 您看到的ImportError可能就是这种现象的征兆。 Generally, if you import a module which in turn imports something else, and the import chain ends up importing the very module that started all the importing, you'll get an ImportError. 通常,如果您导入一个模块,而该模块又导入了其他内容,并且导入链最终导入了开始所有导入的模块,则将出现ImportError。

Can you move CommonClass into a new module module.submod.utils that doesn't import anything else from your code and import it from there? 你可以移动CommonClass到一个新的模块module.submod.utils不会从您的代码导入别的,并从那里进口吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM