他言語経験者用 Python 入門③ ~モジュールとパッケージ~

モジュール

モジュールとは

Pythonのコードを含む拡張子が「py」のテキストファイルであり、関連性のある「プログラム部品」を1つのファイルにまとめたもの。

標準ライブラリ、あるいはインストール済みの外部モジュールを自分のプログラムに導入するには、import 文を使用する。

import 文の基本構文は以下のとおり何種類かある。

import module_name
import module_name as identifier
from module_name import item_name [, item_name ...]

※ 最後の構文について、item_name はモジュール内の関数および変数を指定できる。

自作モジュール

 #circle .py
PI = 3.141592

def area_of_circle(r):
 print(r ** 2 * PI)

def circumference(r):
 print(2 * r * PI)

# 非公開の関数は関数名をアンダースコア「_」で始める
def _secret():
 print('private function')

# さらに強い非公開を表すにはアンダースコアを2つ付ける
def __strong_secret():
 print('secret...')

import 方法各種

 #main .py
from circle import PI
from circle import area_of_circle
import circle

print(PI)
area_of_circle(2)
circle.circumference(3)
実行結果:
 3.141592
 12.566368
 18.849552000000003

パッケージ

パッケージとは

複数のモジュールを束ねたもの。サブパッケージを含めることもできる。

パッケージとして作成するフォルダには、「__init__.py」というファイルを配置する必要がある。
シンプルなパッケージであれば、__init__.pyファイルを置くだけで良い。
パッケージのインポート時に何らかの初期化処理が必要になるのであれば、このファイルにそれらの処理を記述する。

パッケージ作成

パッケージ作成の基本的な手順は以下のとおり。

① パッケージとなるフォルダを作成する。
② __init__.py ファイルをパッケージ内に作成する。
③ モジュールファイルをパッケージ内に作成する。

今回は、以下のような構成で作成した。
mypkg フォルダがパッケージ、その配下に __init__.py とモジュールファイル「circle.py」を置いた。

画像1

circle.py のコードを以下に掲載しておく。

PI = 3.141592

def area_of_circle(r):
 print(r ** 2 * PI)
 
def circumference(r):
 print(2 * r * PI)

パッケージのインポート

全項で作成した mypkg を main.py でインポートしてみる。
※ 先に言っておくと、この方法は失敗する。

# main.py
import mypkg

print(mypkg.circle.PI)
実行結果: AttributeError: module 'mypkg' has no attribute 'circle'

「mypkg には、 circle という属性がない」と怒られてしまった。
パッケージをインポートする方法は何種類かあるが、最も簡単な方法から記載する。

# main.py
import mypkg.circle    # ドットによりパッケージ名とモジュール名まで指定する

print(mypkg.circle.PI)
実行結果: 3.141592

次の方法は、from キーワードを使う。

# main.py
from mypkg import circle    # from パッケージ import モジュール

print(circle.PI)
実行結果: 3.141592

最後に、 __init__.py ファイルを使う方法。

# __init__.py
from mypkg.circle import PI, area_of_circle, circumference
__all__ = ['PI', 'area_of_circle', 'circumference']

・アスタリスクでインポート

# main.py
from mypkg import *

print(PI)
area_of_circle(2)
circumference(3)
実行結果:
 3.141592
 12.566368
 18.849552000000003

・アスタリスクを使わず、使用するもののみを1つずつインポート

from mypkg import PI, area_of_circle, circumference

print(PI)
area_of_circle(2)
circumference(3)
実行結果:
 3.141592
 12.566368
 18.849552000000003


次は 入門④ クラス

この記事が気に入ったらサポートをしてみませんか?