我想从位于当前目录上方的文件中的类继承。
是否可以相对导入该文件?
最佳答案
从 ..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 executefrom . import mod
from a module in thepkg
package then you will end up importingpkg.mod
. If you executefrom ..subpkg2 import mod
from withinpkg.subpkg1
you will importpkg.subpkg2.mod
. The specification for relative imports is contained within PEP 328.
PEP 328处理绝对/相对导入。
https://stackoverflow.com/questions/1054271/