2025年07月09日 更新
どうも、クラゲジュニアです。
Pythonを学んでいると、math.sqrt(2)という記述はモジュール名.関数名という構造は分かるけど、mylist.append(100)という記述の構造は何だっけ?🤔となる場合がありましたので、クラゲジュニアなりの視点で整理してみました。
[TOC]
Pythonには、あらかじめ用意された「組み込み関数」や「組み込み定数」と呼ばれる要素があり、importは不要。
【組み込み関数】
print(), len(), range(), type(), int(), str(), list(), dict(), float(), input(), sum(), max(), min(), abs(), sorted(), zip(), enumerate(), isinstance(), map(), filter(), any(), all(), bool(), set(), tuple(), reversed(), open(), id(), chr(), ord(), pow(), divmod(), bin(), hex(), oct(), round(), dir(), help(), eval(), exec(), globals(), locals(), vars(), callable(), getattr(), setattr(), hasattr(), delattr(), compile(), format(), hash(), iter(), next(), slice(), super(), frozenset(), memoryview(), object(), complex(), ascii(), breakpoint(), __import__()
【組み込み定数】
True, False, None, NotImplemented, Ellipsis, __debug__, quit, exit
# 組み込み関数
print('hello')
# 組み込み定数
result = True
💡ポイント:関数や定数を使用するのにドットは不要で
要素名だけでOK
モジュールをimportすることで、そのモジュールが提供する関数や定数を使えるようになる。モジュールには、pip installなしですぐに使える「標準ライブラリのモジュール」と、pip installで追加して使う「外部ライブラリのモジュール」がある。
【標準ライブラリのモジュール例】
os, sys, math, datetime, random, re, json, pathlib, collections, itertools, etc
【外部ライブラリのモジュール例】
numpy, pandas, matplotlib, requests, scikit-learn, tensorflow, flask, pytest, seaborn, beautifulsoup4, etc
# モジュール読み込み
import math
# モジュール関数
r = math.sqrt(2)
#モジュール定数
p = math.pi
💡ポイント:関数や定数を使用するのに
モジュール名.要素名で記述する
※ユーザー定義関数は割愛
Pythonには「組み込みクラス」と呼ばれる基本的なデータ型があり、明示的に型指定しなくても、Pythonが自動的に適切な型として認識してくれる。
【組み込みクラス】
整数型(int), 文字列型(str), リスト(list), 辞書(dict), 浮動小数点数(float), ブール値(bool), タプル(tuple), 集合型(set), 複素数型(complex), バイト列(bytes)
# 組み込みクラス(リスト型)のインスタンスを生成
mylist = []
# 組み込みクラスのメソッド
mylist.append(100)
# 組み込みクラスのプロパティ
# リスト型を含む組み込みクラスの多くはプロパティがないので割愛
mylist = []の時点で、リストクラスのインスタンスが生成されている点がポイント。
組み込みクラスとは異なり、標準ライブラリや外部ライブラリに含まれるクラスは、importしてから使う必要がある。これらにはpip installなしですぐに使える「標準ライブラリのクラス」と、pip installで追加して使う「外部ライブラリのクラス」がある。
【標準ライブラリのクラス例】
datetime.date, datetime.datetime, pathlib.Path, collections.Counter, json.JSONDecoder, re.Match, itertools.chain, math.ceil, os.DirEntry, sys.float_info, etc
【外部ライブラリのクラス例】
numpy.ndarray, pandas.DataFrame, matplotlib.pyplot.Figure, requests.Response, sklearn.linear_model.LogisticRegression, tensorflow.Tensor, bs4.BeautifulSoup, flask.Flask, seaborn.axisgrid.FacetGrid, pytest.raises, etc
# モジュール読み込み(datetimeモジュールからdateクラス読み込み)
from datetime import date
# クラスのインスタンス生成
d = date(2025, 7, 9)
# クラスのメソッド
w = d.weekday()
# クラスのプロパティ
y = d.year
💡ポイント:メソッドやプロパティを使用するのに
インスタンス名.要素名で記述する
※ユーザー定義クラスは割愛
関数名、定数名モジュール名.関数名、モジュール名.定数名インスタンス名.メソッド名、インスタンス名.プロパティ名ということで、mylist.append(100)という記述は、組み込みクラスである「リスト型」のインスタンスmylistに対して、メソッドappend()を呼び出しているものでした。
以上です。