简体   繁体   English

无法导入名称 <MyClass> 在Python中

[英]Cannot import name <MyClass> in Python

I try to import a class in python but I get some trouble probably because of cyclic import but I don't know how to solve my problem. 我尝试在python中导入一个类,但是可能由于循环导入而遇到了一些麻烦,但是我不知道如何解决我的问题。

The loop that appears in my traceback (packageA contains three files: A, B and C): 我的回溯中出现的循环(packageA包含三个文件:A,B和C):

**In main.py**    
from packageA import fileA
**In fileA.py:**
from packageA import fileB    <- 
**In fileB.py:**
from packageA import fileC
**In fileC.py:**
from fileB import ClassB      <-

I get: 我得到:

ImportError: cannot import name ClassB

At first, I thought that I could delete "import ClassB" from fileC as the whole fileB had already been imported before. 起初,我认为我可以从fileC中删除“ import ClassB” ,因为之前已经导入了整个fileB。 But if I try so I get another error which is: 但是,如果我尝试这样做,则会收到另一个错误,它是:

NameError: global name 'ClassB' is not defined

Can someone help? 有人可以帮忙吗?

This is a case of circular imports . 这是循环进口的情况。 fileB is importing fileC, which is importing fileB. fileB正在导入fileC,后者正在导入fileB。 The latter import is being satisfied with an empty, uninitialized module object. 后一个导入由一个空的,未初始化的模块对象满足。

In general, you do not want to use circular imports. 通常,您不想使用循环导入。

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

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