如何导入上述目录中的Python类? [英] How to import a Python class that is in a directory above?
问题描述
我想继承自位于当前目录之上的文件中的类。
I want to inherit from a class in a file that lies in a directory above the current one.
是否可以相对导入该文件?
Is it possible to relatively import that file?
推荐答案
在包层次结构中,使用两个点,如 import statement doc说:
Inside a package hierarchy, use two dots, as the import statement doc says:
指定什么要导入的模块不必指定模块的绝对名称。当模块或软件包包含在另一个软件包中时,可以在相同的顶部软件包中进行相对导入,而无需提及软件包名称。通过在中的
之后使用指定模块或包中的引导点,您可以指定在不指定确切名称的情况下遍历当前包层次结构的高度。一个领先的点表示存在导入模块的当前包。 两个点表示一个包级别。三个点上升两个等级,所以如果你执行
执行。从
,那么您将最终导入pkg
包中的模块导入modpkg.mod
。如果从pkg.subpkg1
中的..subpkg2 import mod,则您将导入
pkg .subpkg2.mod
。相对导入的规范包含在 PEP 328 中。
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 处理绝对/相对进口。
PEP 328 deals with absolute/relative imports.
这篇关于如何导入上述目录中的Python类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!