python - 如何导入上面目录中的 Python 类?

我想从位于当前目录上方的文件中的类继承。

是否可以相对导入该文件?

最佳答案

从 ..subpkg2 导入模组

根据 Python 文档:在包层次结构中,使用两个点,如 import statement医生说:

When specifying what module to import you do not have to specify the absolute name of the module. When a module or package is contained within another package it is possible to make a relative import within the same top package without having to mention the package name. By using leading dots in the specified module or package after from you can specify how high to traverse up the current package hierarchy without specifying exact names. One leading dot means the current package where the module making the import exists. Two dots means up one package level. Three dots is up two levels, etc. So if you execute from . import mod from a module in the pkg package then you will end up importing pkg.mod. If you execute from ..subpkg2 import mod from within pkg.subpkg1 you will import pkg.subpkg2.mod. The specification for relative imports is contained within PEP 328.

PEP 328处理绝对/相对导入。

https://stackoverflow.com/questions/1054271/

相关文章:

python - 如何在 python 中发送带有请求的 "multipart/form-data"

datetime - 组合 datetime.date 和 datetime.time 对象的 Py

linux - 使用 sudo 时找不到命令

linux - 如何使用 grep 在当前目录中搜索具有字符串 "hello"但仅显示 .h 和 .

linux - 如何在linux中列出空文件夹

linux - 如何使用文件的行作为命令的参数?

python - 将 [key1,val1,key2,val2] 转换为字典?

python - Django:为什么有些模型字段会相互冲突?

python - 在没有运行 X 服务器的情况下生成 matplotlib 图

linux - 哪个更好,curl 还是 wget?