如何导入上述目录中的Python类? [英] How to import a Python class that is in a directory above?

查看:109
本文介绍了如何导入上述目录中的Python类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 包中的模块导入mod ,那么您将最终导入 pkg.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 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 处理绝对/相对进口。

PEP 328 deals with absolute/relative imports.

这篇关于如何导入上述目录中的Python类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆