他モジュールに定義したクラスをインポートする方法

はじめに

クラスを別ファイル化する方法を毎回忘れてしまうのでメモ。module1に定義したHumanクラスをmodule2で使用する方法。

階層構造

test
  ├─module1.py
  └─module2.py

コード

module1.pyの記述

class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "名前:" + str(self.name) + " 年齢:" + str(self.age)

module2の記述

from module1 import Human

hu1 = Human("john", 21)
hu2 = Human("Bob", 22)

print(hu1)
print(hu2)

module2を実行するとこんな感じ。

test/module2.py
名前:john 年齢:21
名前:Bob 年齢:22

Process finished with exit code 0

備考

module2を実行した際、from module2 import Humanの時点でmodule2が全行読まれる。例えばmodule2に

class Human:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "名前:" + str(self.name) + " 年齢:" + str(self.age)

print("test2")

print("test2")を追加し、module1を実行すると

test/module2.py
test2
名前:john 年齢:21
名前:Bob 年齢:22

Process finished with exit code 0

このようにtest2が表示される。