皆さんはPythonを便利にするために型を自分で定義したことはありますか?
そこでデータ型を定義するとき最も大切なのは特殊メゾットというものです。
特殊メソットはアンダーバー4個の間に英語を入力して定義できます。
特殊メソットの役割は簡単に言うと
「データ型を関数で使った時のふるまいを定義する関数」
です。
図で説明すると、
主に下のような特殊メゾットがあります。
| 特殊メソット | 機能 |
|---|---|
__add__(self, other) |
self + otherの計算のふるまいを定義 |
__pos__(self) |
+selfの計算のふるまいを定義 |
__sub__(self, other) |
self - otherの計算のふるまいを定義 |
__neg__(self) |
-selfの計算のふるまいを定義 |
__pow__(self, other) |
self ** otherの計算のふるまいを定義 |
__truediv__(self, other) |
self / otherの計算のふるまいを定義 |
__floordiv__(self, other) |
self // otherの計算のふるまいを定義 |
__divmod__(self, other) |
self % otherの計算のふるまいを定義 |
__round__(self, other) |
round(self, other)の計算のふるまいを定義 |
__eq__(self, other) |
self == otherのふるまいを定義 |
__ne__(self, other) |
self != otherのふるまいを定義 |
__lt__(self, other) |
self < otherのふるまいを定義 |
__gt__(self, other) |
self > otherのふるまいを定義 |
__le__(self, other) |
self <= otherのふるまいを定義 |
__ge__(self, other) |
self >= otherのふるまいを定義 |
__lshift__(self, other) |
self << otherのふるまいを定義 |
__lshift__(self, other) |
self >> otherのふるまいを定義 |
__and__(self, other) |
self and otherのふるまいを定義 |
__or__(self, other) |
self or otherのふるまいを定義 |
__xor__(self, other) |
self ^ otherのふるまいを定義 |
__not__(self) |
not selfのふるまいを定義 |
__abs__(self) |
abs(self)のふるまいを定義 |
__len__(self) |
len(self)のふるまいを定義 |
__int__(self) |
int(self)のふるまいを定義 |
__str__(self) |
str(self)のふるまいを定義 |
__float__(self) |
float(self)のふるまいを定義 |
__list__(self) |
list(self)のふるまいを定義 |
__getitem__(self, other) |
要素の参照( self[other])のふるまいを定義 |
__setitem__(self, other1, other2) |
要素の置換( self[other1] = other2)のふるまいを定義 |
__delitem__(self, other) |
要素の削除( del self[other1])のふるまいを定義 |
__hash__(self) |
hash(self)のふるまいを定義辞書型などで使用するときには必須 |
__contains__(self, other) |
other in selfのふるまいを定義 |
__iter__(self) |
for ~~~ in self:の最初の処理を定義 |
__next__(self) |
for value in self:が繰り返すごとに行われる処理raise StopIterationを実行することでループを抜ける値を返すと valueに代入される |
__del__(self) |
del selfのふるまいを定義 |
__call__(self, other1, ...) |
self(other1, ...)のふるまいを定義関数として利用するときの定義 |
__format__(self) |
"{}...".format(self)のふるまいを定義 |
もしself += otherの※ふるまいを変えるときは
__add__(self, other)のaddの前に"i"を付けた__iadd__(self, other)を追加して定義できます。
self *= otherも※同じように
__mul__(self, other)のmulの前に"i"を付けた__imul__(self, other)を追加して定義できます。
※__add__(self, other)が定義されていたら基本的にはself += otherはself = self + otherと勝手に定義される。
※__mul__(self, other)も同じように定義されていたら基本的にはself *= otherはself = self * otherと勝手に定義される。
↓重要↓
もしother + self(selfは自作データ型)を有効にするときは
__add__(self, other)のaddの前に"r"を付けた__radd__(self, other)をclass データ型に追加して定義できます。
other - self(selfは自作データ型)も同じように
__sub__(self, other)のsubの前に"r"を付けた__rsub__(self, other)をclass データ型に追加して定義できます。
hmath.×××(self)などライブラリの関数のふるまいを変えたいときは__×××__(self)が使えます。
是非今回のことを活用してください。