Python のサブディレクトリからクラスをインポートする
このチュートリアルでは、Python のサブディレクトリからクラスをインポートする方法について説明します。
Python 3 の import ステートメントを使用してサブディレクトリからクラスをインポートする
Python 3.x では、現在のサブディレクトリまたは任意のサブディレクトリからクラスをインポートするのは非常に簡単です。このチュートリアルでは、次のディレクトリ構造を使用します。
Main/
main.py
A.py
B/
B.py
ファイル A.py と B.py には、Aclass と Bclass の 2つのクラスが含まれており、これらを main.py クラスにインポートします。A.py と B.py の両方のコードを以下に示します。
A.py ファイル:
class Aclass:
a = 5
def show(this):
print("Hello! this is class A")
B.py ファイル:
class Bclass:
b = 5
def show(this):
print("Hello! this is class B")
import ステートメントは、main.py の Aclass と Bclass をインポートします。次のコード例は、Python の import ステートメントを使用してサブディレクトリからクラスをインポートする方法を示しています。
from A import Aclass
from B.B import Bclass
var1 = Aclass()
var2 = Bclass()
var1.show()
var2.show()
出力:
Hello! this is class A
Hello! this is class B
上記のコードでは、import ステートメントを使用して、main.py ファイルに Aclass と Bclass の両方をインポートします。同じディレクトリ内のファイルについては、次の表記を使用する必要があります。
from filename import classname
filename はファイルの名前であり、classname はインポートされるクラスの名前です。サブディレクトリ内のファイルについては、次の表記に従う必要があります。
from dirname.filename import classname
dirname はファイルが配置されているディレクトリの名前、filename はファイルの名前、classname はインポートされるクラスの名前です。サブディレクトリまたはサブサブディレクトリ内のファイルの場合、以下に示すように、別の .subdirname を追加する必要があります。
from dirname.subdirname.filename import classname
dirname はディレクトリの名前、subdirname はファイルを含むサブディレクトリの名前、filename はファイルの名前、classname はクラスの名前です。インポートされました。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn