从同级目录导入

发布于 2024-10-09 12:38:34 字数 201 浏览 0 评论 0原文

我有一个名为“ClassA”的Python 类和另一个Python 类,该类应该导入ClassA(即“ClassB”)。目录结构如下:

MainDir
../Dir
..../DirA/ClassA
..../DirB/ClassB

如何使用sys.path让ClassB可以使用ClassA?

I have a Python class called "ClassA" and another Python class which is supposed to import ClassA which is "ClassB". The directory structure is as follows:

MainDir
../Dir
..../DirA/ClassA
..../DirB/ClassB

How would I use sys.path so that ClassB can use ClassA?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七堇年 2024-10-16 12:38:34

作为问题“Python从父目录导入”的字面答案:

导入当前模块父目录中的“mymodule”:

import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir) 
import mymodule

edit< /b>
不幸的是,__file__ 属性并不总是被设置。
获取parentdir的更安全的方法是通过inspect模块:

import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)

as a literal answer to the question 'Python Import from parent directory':

to import 'mymodule' that is in the parent directory of your current module:

import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir) 
import mymodule

edit
Unfortunately, the __file__ attribute is not always set.
A more secure way to get the parentdir is through the inspect module:

import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
超可爱的懒熊 2024-10-16 12:38:34

您可以使用相对导入(来自链接的示例,当前模块 - ABC):

from . import D                 # Imports A.B.D
from .. import E                # Imports A.E
from ..F import G               # Imports A.F.G

You can use relative import (example from link, current module - A.B.C):

from . import D                 # Imports A.B.D
from .. import E                # Imports A.E
from ..F import G               # Imports A.F.G
酒绊 2024-10-16 12:38:34

你真的应该使用包。然后MainDir被放置在sys.path上文件系统中的某个点(例如.../site-packages),然后你可以在ClassB中说:

from MainDir.Dir.DirA import ClassA # which is actually a module

你只需放置名为__init__.py的文件在每个目录中使其成为包层次结构。

You really should be using packages. Then MainDir is placed at a point in the file system on sys.path (e.g. .../site-packages), then you can say in ClassB:

from MainDir.Dir.DirA import ClassA # which is actually a module

You just have to place files named __init__.py in each directory to make it a package hierarchy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文