从同级目录导入
我有一个名为“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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为问题“Python从父目录导入”的字面答案:
导入当前模块父目录中的“mymodule”:
edit< /b>
不幸的是,
__file__
属性并不总是被设置。获取parentdir的更安全的方法是通过inspect模块:
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:
edit
Unfortunately, the
__file__
attribute is not always set.A more secure way to get the parentdir is through the inspect module:
您可以使用相对导入(来自链接的示例,当前模块 -
ABC
):You can use relative import (example from link, current module -
A.B.C
):你真的应该使用包。然后MainDir被放置在sys.path上文件系统中的某个点(例如.../site-packages),然后你可以在ClassB中说:
你只需放置名为
__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:
You just have to place files named
__init__.py
in each directory to make it a package hierarchy.