【问题标题】:How to import Python file universally from the same folder and from outer?如何从同一文件夹和外部通用导入 Python 文件?
【发布时间】:2021-06-16 02:23:59
【问题描述】:

我有文件层次结构:
文件夹
|
课程
|
类1.py
class2.py
test_class2.py
main.py
抱歉,我找不到如何标记文本。 Main.py 和 classes 文件夹在同一个文件夹中。
Main.py 从 class2.py 导入 from classes.class2 import someclass.
class2.py 从 class1.py 导入 from classes.class1 import someanotherclass.
这在运行 main.py 的情况下非常有效。问题是如果我想在文件夹“classes”中测试class2.py,我总是需要将import 更改为from class1.py import someanotherclass。 那么在这两种情况下有没有通用的方法来导入它,以便 main.py 和 class2.py 正常工作?

【问题讨论】:

  • 您可以尝试将您的导入包装起来...除了在 ImportError 的情况下您从“其他”位置导入您的模块。
  • @MikeScotty 谢谢!

标签: python class import


【解决方案1】:

我会假设 relative imports 是您正在寻找的: https://docs.python.org/3/reference/import.html#package-relative-imports

main.py

from classes.class2 import someclass

类/class2.py

from .class1 import someanotherclass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 2021-11-12
    • 2019-06-17
    相关资源
    最近更新 更多