python3 モジュール

モジュールはpythonコードをまとめたファイル
(例:re.py、sys.pyなど標準ライブラリに入ってたりする)
普段は import 文でモジュールを読み込み、変数をプログラム内で使えるようになる

 #report .py(モジュールファイル)
def get_desc():
   from random import choice
   pos=["rain","snow","sleet","fog","sun","who knows"]
   return choice(pos)
 #weather .py
import report
description = report.get_description()
print("Today's weather:", description)
#※VScodeでweather.pyを実行
C:python.exeの起動"ファイルの場所/weather.py"
Today's weather: snow

C:python.exeの起動"ファイルの場所/weather.py"
Today's weather: fog

C:python.exeの起動"ファイルの場所/weather.py"
Today's weather: sun

作ったモジュールは実行するプログラムと同じフォルダ内にないと起動しない

import モジュール名 はモジュール全体をインポートし、
from モジュール名 import 関数 でモジュール内の関数のみをインポートする

 #weather2 .py
import report as wt
description = wt.get_description()
print("Today's weather:", description)

import モジュール名 as 別名 でモジュールを簡潔な名前に変えることができる

 #weather3 .py
from report import get_description as gd
description = gd()
print("Today's weather:", description)

from モジュール名 import 関数 as 別名 でモジュール含む関数名を簡略化できる

 #daily .py
def forecast():
   return "like yesterday"
 #weekly .py
def forecast():
   return ["rain","snow","more snow","sleet","fog","sun","who knows"]
 #weather2 .py
from sources import daily, weekly

print("Daily:",daily.forecast())
print("Weekly:")
for w in weekly.forecast():
   print(w)
    #出力
Daily: like yesterday
Weekly:
rain
snow
more snow
sleet
fog
sun
who knows

フォルダ名/weather2.py
フォルダ名/sources/daily.py
フォルダ名/sources/weekly.py

メインプログラム(weather2.py)が入っている場所にフォルダを作成し、
フォルダ内にモジュール(daily.py,weekly.py)を作成、
from フォルダ名 import モジュール1,モジュール2
階層を分けてモジュールをインポートできる(パッケージ)

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