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?

More than 1 year has passed since last update.

WindowsによるPython入門 #11: モジュール

Last updated at Posted at 2023-02-24

はじめに

今回はモジュールを解説します。

YouTube動画

モジュールの定義と使用

.pyファイルを作成すると、それがモジュールになります。

sample.py
NUM = 10
def get_number():
    return NUM

モジュールを使用するには、import 文を使用します。

main.py
import sample
print(sample.get_number() + 20)  # sample モジュールの get_number() 関数を呼び出し

コマンドプロンプトから main.py を実行します。

>py main.py
30

別名でインポート

as を使用すると、モジュールに別名を付けられます。

main.py
import sample as s  # sample モジュールを s という名前でインポート
print(s.get_number() + 20)

一部をインポート

from を使用すると、モジュール内の一部の内容をインポート出来ます。

main.py
from sample import get_number  # sample モジュール内の get_number のみインポート
print(get_number() + 20)

「*」を使用すると、モジュール内の全ての内容をインポート出来ます。

main.py
from sample import *  # sample モジュール内の全ての内容をインポート
print(NUM + 20)

_main_ に関して

モジュール自身の名前を __name__ で取得出来ます。

main.py
import sample
print(sample.__name__)
print(__name__)

以下、実行結果です。

sample
__main__

実行中のモジュールは、"__main__" という文字列が返ります。
ですので、py コマンド(python コマンド) で実行した場合のみ実行されるコードを書くには以下のようにします。

import sample

def main():
    print(sample.get_number() + 20)

if __name__ == "__main__":  # py コマンドで実行した場合のみ実行される(importでは実行されない)
    main()

main() という関数名は慣例的に使用されますが、何でも構いません。
if 文のブロック内がモジュールの import 時には実行されず、py コマンドで実行した時のみ実行されます。

おわりに

以上、モジュールに関して解説しました。
今回が最終回になります。
お疲れ様でした。

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?