python中的导入语句混乱
我想在通用 python 文件中导入许多文件,然后在当前模块中需要导入的模块时包含该文件。如果使用 from x import y ,这当然会导致错误并重新导入,但是当使用“正常”导入语句时,我最终会得到很长的指令语句,例如:
x = importModule.directoryName1.directoryName2.moduleName.ClassName()
而我想执行以下操作:
x = importModule.ClassName()
但是正如我之前所说,这样做:
from importModule.directoryName1.directoryName2.moduleNam import ClassName
在一般文件中不起作用,因为我在 ClassName 中包含了 importModule。
所以,我基本上想知道是否有任何解决方案(类似于 using 语句,例如 C++ 中的语句,也许?)
I want to have a number of files imported in a general python file and then include that file when I need the imported modules in the current module. This of course will lead to errors and re-imports if using the from x import y, however when using the "normal" import statement I end up with long instruction statements, for example:
x = importModule.directoryName1.directoryName2.moduleName.ClassName()
whereas I'd like to do the following:
x = importModule.ClassName()
but as I said before, doing this:
from importModule.directoryName1.directoryName2.moduleNam import ClassName
in a general file doesn't work since I include importModule in ClassName.
So, I'm basically wondering if there's anyway around this (something like an using statement, such as the one in C++, perhaps?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来你有递归导入(
importModule
指的是moduleName
,而moduleName
指的是importModule
。如果当您重构时,您应该能够使用要重构,您可以更改
moduleName
中导入内容的顺序,以便ClassName
的类定义出现在>importModule
import; 只要每个文件在尝试导入其他模块之前定义了其他模块所需的引用,那么另一种重构方法就可以解决:您始终可以导入
ClassName 在使用它的函数中;只要在导入
moduleName
之前不调用该函数,就可以最好的方式进行重构 。 ,是将一些类或引用移动到它们自己的模块中,这样就不会出现
A
导入B
和的情况B
导入A
这将解决您的问题,并且使维护工作变得更容易。It sounds like you've got recursive imports (
importModule
refers tomoduleName
, andmoduleName
refers toimportModule
. If you refactor, you should be able to useTo refactor, you can change the order in which things are imported in
moduleName
so that the class definition ofClassName
occurs before theimportModule
import; as long as each file defines the references needed by the other module before they try and import the other module, things will work out.Another way to refactor: you could always import
ClassName
within the function where it's used; as long as the function isn't called beforemoduleName
is imported, you'll be fine.The best way to refactor, though, is to move some classes or references into their own module, so you don't have any situation where
A
importsB
andB
importsA
. That will fix your problem, as well as make it easier to maintain things going forward.嗯,你可以这样做,
但是这有点丑陋而且非常令人困惑,并且不会为稍后阅读你的代码的 Python 程序员赢得很多分数。
Well, you could do
but that's kind of ugly and very confusing, and won't score you a lot of points with the Python programmers who read your code later.