假设我有以下目录结构:
parent_dir/
foo_dir/
foo.py
bar_dir/
bar.py
如果我想从
bar.py
内部导入 foo.py
,我该怎么做?
如果所有出现的目录都是Python packages,即它们都包含
__init__.py
,那么你可以使用
from ..bar_dir import bar
如果目录不是 Python 包,你可以通过使用
sys.path
来完成此操作,但你不应该这样做。
您可以使用
sys
和 os
模块进行通用导入。在foo.py
中从线条开始
import sys
import os
sys.path.append(os.path.abspath('../bar_dir'))
import bar
假设您有以下结构:
root
|_ productconst.py
|_ products
|_ __init__.py
如果你想在
products.__init__
中导入productconst,那么可以使用以下方法:
from ..productconst import *
如果您在 python 3+ 中遇到问题,以下内容对我有用
sys.path.append("..")
。
sys.path.append("..")
from bar_dir import bar
大多数提议的答案都依赖于改变
sys.path
。恕我直言 - 如果您可以正确保留相对文件夹结构,则没有必要。
请参阅我的示例:
class Bar():
def __init__(self) -> None:
pass
def __repr__(self) -> str:
return "This is an instance of Bar"
def some_method(self) ->None:
pass
from .bar import Bar
from ..bar_dir import Bar
class Foo():
def __init__(self ,bar_instance: Bar) -> None:
self._bar=bar_instance
def __repr__(self) -> str:
return f"You are inside an instance of Foo and you have just accessed bar={self._bar}"
from .foo import Foo
import parent_dir.bar_dir as bar_lib
import parent_dir.foo_dir as foo_lib
if __name__ == "__main__":
f=foo_lib.Foo(bar_instance=bar_lib.Bar())
print(f"This is an instance of foo={f}")
print(f"{bar_lib.Bar()}")