0
1

More than 1 year has passed since last update.

Pythonモジュールの基本

Last updated at Posted at 2023-08-04

モジュール、パッケージ、ライブラリ

モジュール

関数や、クラスをコードで取り入れることができる定義や文が入ったファイル(スクリプトファイル、.pyがついたファイル一つ一つ)

パッケージ

複数のモジュールがまとまったもの
int.pyという名前のファイルを持つ
・__path__属性を持つ

ライブラリ

モジュールとパッケージを集めたもの

image.png

・import ・from ・asの使い方

import

calc.py

def square(num):
    return num**2

def cube(num):
    return num***3
>>> import calc
>>> calc.square(2) # モジュール名.関数名
4

・関数にはモジュール名を使ってアクセス

・ローカルな名前に代入できる

from

特定の関数をインポート

>>> from calc import cube
>>> cube(3)
27

from モジュール名 import *

_(アンダースコア)以外で始まる全ての名前(クラス・関数)

def _check_tzinfo_arg(tz):
    if tz is not None and not isinstance(tz, tzinfo):
        raise TypeError("tzinfo argument must be None or of a tzinfo subclass")

class timedelta:

・このようにアンダースコアがついてる関数は公開したくないもの
・内部で使いたい関数と外部で使いたい関数によって使い分ける

as

指定した名前でインポート

>>> import calc as cl
>>> cl.cube(4)
64

モジュール名が長い時に、省略したい場合などに使用

モジュールについて

・変数にもアクセス可能

test3.py

a = 5
>>> import test3
>>> print(test3.a)
5

>>> test3.a = 9
>>> print(test3.a)
9

・モジュールは1回しかインポートされない
モジュールを修正した場合は、再起動かimportib.reload()を使う(以下)

>>> import importlib
>>> importlib.reload(test_module)

・__name__の値がモジュール名

test1.py
モジュール名を出力する関数

def test_func():
    print(__name__)

test_func()

呼び出し
test2.py

import test1
>>> test1 # モジュール名が呼び出される

次のような書き方をすると出力値が変わる

python test1.py
>>> __main__

・トップレベルで使用する場合は__main__となる
・if name == "main":
このモジュールはトップレベルで実行するなら〜という意味になる

0
1
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
1