0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

__init__.pyの直感的な説明

0
Last updated at Posted at 2026-07-11

__init__.pyがなぜ必要なのか、初学者のメモ。(正確な説明ではない。)

__init__.pyの役割

・ディレクトリをPythonのパッケージとして扱うためのファイル(昔は必須、python3.3以降は必須ではない)。
・ディレクトリ名から直接関数を呼び出せるようにできる。

通常のインポート

通常、関数をインポートするときは、ディレクトリ名とファイル名の両方を書く必要がある。

from sample.math_utils import add

ここでは、

・ sample:ディレクトリ
・ math_utils:ファイル
・ add:関数

を指定している。

__init__.pyを使う場合

ディレクトリ直下に__init__.pyを置き、その中で他のファイルから関数をインポートしておく。

#sample/__init__.py
from .math_utils import add

すると、ユーザーはファイル名を書かずに、

from sample import add

と書ける。

これは、Pythonがsampleをインポートしたときに、自動でsample/__init__.pyを実行し、その中で読み込まれたaddを利用できるようになるためである。

参照
・Python の __init__.py とは何なのか
https://qiita.com/msi/items/d91ea3900373ff8b09d7

・chatGPT

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?