Python包不是相对于当前目录的吗?

2024-05-12 19:08:00 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我有一个如下的文件结构:

  • 你知道吗主.py/你知道吗
  • 帕奎特/
    • __初始值
    • 测试1.py

这就是我的生活主.py地址:

from paquete import testFunc


def main():
    testFunc()


if __name__ == '__main__':
    main()

这是我在test1.py中得到的:

def testFunc():
    print("Hello from test1 function!")

这就是我在初始化中得到的:

from test1 import testFunc

但这不起作用,它说没有名为test1的模块。你知道吗

但是,如果我有以下情况:

from paquete.test1 import testFunc

它工作得很好。但是我不明白,如果它和test1在同一个目录中,为什么我需要在它前面加上目录名,就好像我在项目的根级别工作一样?你知道吗


Tags: 文件namefrompyimporthelloifmain
2条回答

您当前使用的是所谓的隐式相对导入。在python3.x中它被弃用,这在PEP 8中提到。你知道吗

您仍然可以使用相对导入;它只需要使用下面描述的带有前导点的syntax

These imports use leading dots to indicate the current and parent packages involved in the relative import.

# Relative
from .test1 import testFunc

# Absolute
from paquete.test1 import testFunc

也是reference-

The only acceptable syntax for relative imports is from .[module] import name. All import forms not starting with . are interpreted as absolute imports. (PEP 0328).

这是因为paquete在您的sys.path中,但包的内部不是。因此,您可以为paquete包进行绝对导入,但只能为其内部进行相对导入。paquete在你身上sys.path因为它在同一个目录中,你呢主.py. 你知道吗

您可以在导入之前设置__path__属性,以获得import语句要考虑的包的内部信息。你知道吗

请看这个以供参考https://docs.python.org/3/reference/import.html#module-path

相关问题 更多 >