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

查看:23
本文介绍了如何导入上面目录中的 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?

推荐答案

from ..subpkg2 import mod

根据 Python 文档:在包层次结构中,使用两个点,作为 import 语句 doc 说:

Per the Python docs: When inside a package hierarchy, use two dots, as the import statement doc says:

在指定要导入的模块时,您不必指定模块的绝对名称.当一个模块或包包含在另一个包中时,可以在同一个顶级包中进行相对导入,而无需提及包名称.通过在from 之后的指定模块或包中使用前导点,您可以指定向上遍历当前包层次结构的高度,而无需指定确切名称.一个前导点表示进行导入的模块所在的当前包.两个点表示上一层包.三个点是两个级别,等等.所以如果你执行 from .从 pkg 包中的一个模块导入 mod 然后你将最终导入 pkg.mod.如果您从 pkg.subpkg1 中执行 from ..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天全站免登陆