在 python 2 中,我可以创建这样的模块:
parent
->module
->__init__.py (init calls 'from file import ClassName')
file.py
->class ClassName(obj)
这行得通。在 python 3 中,我可以从命令解释器做同样的事情并且它有效(编辑:这有效,因为我在运行解释器的同一目录中)。但是,如果我创建 __ init __.py 并像这样执行相同的操作:
"""__init__.py"""
from file import ClassName
"""file.py"""
class ClassName(object): ...etc etc
我收到 ImportError: cannot import name 'ClassName', 它根本看不到 'file'。它会在我导入模块后立即执行此操作,即使我可以通过直接引用它来导入所有内容(我不想这样做,因为它与我们的代码库的其余部分完全不一致)。给了什么?
最佳答案
在 python 3 中,所有导入都是绝对的,除非给出相对路径来执行导入。您将需要使用绝对导入或相对导入。
绝对导入:
from parent.file import ClassName
相对导入:
from . file import ClassName
# look for the module file in same directory as the current module
关于python - 如何从 Python 3 中的当前目录中的文件导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31269437/