「ClassA」というPythonクラスと、「ClassB」であるClassAをインポートすることになっている別のPythonクラスがあります。ディレクトリ構造は次のとおりです。
MainDir
../Dir
..../DirA/ClassA
..../DirB/ClassB
sys.path
ClassBがClassAを使用できるようにするにはどうすればよいですか?
「 Python Import from parent directory 」という質問に対する文字通りの回答として:
現在のモジュールの親ディレクトリにある「mymodule」をインポートするには:
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0,parentdir)
import mymodule
edit
残念ながら、__file__
属性は常に設定されているわけではありません。親ディレクトリを取得するより安全な方法は、検査モジュールを使用することです。
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
相対インポートを使用できます(リンクの例、現在のモジュール - A.B.C
):
from . import D # Imports A.B.D
from .. import E # Imports A.E
from ..F import G # Imports A.F.G
本当にパッケージを使用する必要があります。次に、MainDir が sys.path 上のファイル システムのあるポイント (例: .../site-packages) に配置され、ClassB で次のように言うことができます。
from MainDir.Dir.DirA import ClassA # which is actually a module
__init__.py
パッケージ階層を作成するには、各ディレクトリに名前を付けたファイルを配置するだけです。