如何从同一目录导入python类文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21139364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to import python class file from same directory?
提问by Yablargo
I have a directory in my Python 3.3 project called /models.
我的 Python 3.3 项目中有一个名为 /models 的目录。
from my main.pyI simply do a
从我的main.py我只是做了一个
from models import *
in my __init__.py:
在我的__init__.py:
__all__ = ["Engine","EngineModule","Finding","Mapping","Rule","RuleSet"]
from models.engine import Engine,EngineModule
from models.finding import Finding
from models.mapping import Mapping
from models.rule import Rule
from models.ruleset import RuleSet
This works great from my application.
这在我的应用程序中效果很好。
I have a model that depends on another model, such that in my engine.pyI need to import finding.pyin engine.py. When I do: from finding import Finding
我有一个模型依赖于其他模型,使得我的engine.py,我需要进口finding.py的engine.py。当我做:from finding import Finding
I get the error No Such Module exists.
我收到错误No Such Module exists。
How can I import class B from file A in the same module/directory?
如何从同一模块/目录中的文件 A 导入类 B?
Edit 1:Apparently I can do: from .finding import Findingand this works. And the answer below reflects this as well so I guess this is reasonably correct. I've fixed up my file naming and moved my tests to a different directory and I am running smoothly now. Thanks!
编辑 1:显然我可以做到:from .finding import Finding这有效。下面的答案也反映了这一点,所以我想这是相当正确的。我已经修复了我的文件命名并将我的测试移动到不同的目录,我现在运行顺利。谢谢!
采纳答案by RemcoGerlich
Since you are using Python 3, which disallows these relative imports (it can lead to confusion between modules of the same name in different packages).
由于您使用的是 Python 3,它不允许这些相对导入(这可能导致不同包中同名模块之间的混淆)。
Use either:
使用:
from models import finding
or
或者
import models.finding
or, probably best:
或者,可能是最好的:
from . import finding # The . means "from the same directory as this module"

