関数名の前後に2つのアンダースコアをつけたクラス関数は特殊メソッドとして扱われる.
例: def __FUNC__(self, ...):
演算子のオーバーロードとして定義できるメソッドは以下の通り.
- object.__add__(self, other): object + other
- object.__sub__(self, other): object - other
- object.__mul__(self, other): object * other
- object.__truediv__(self, other): object / other
- object.__floordiv__(self, other): object // other
- object.__mod__(self, other): object % other
- object.__lt__(self, other): object < other
- object.__le__(self, other): object <= other
- object.__eq__(self, other): object == other
- object.__ne__(self, other): object != other
- object.__gt__(self, other): object > other
- object.__ge__(self, other): object >= other
__getitem__と__setitem__はobject[key]という形でアクセスするための特殊メソッド
- object.__getitem__(self, key): keyに該当する値を返す
- object.__setitem__(self, key, value): keyに該当する値をvalueに設定・変更する
- object.__contain__(self, item): itemが存在するか返す
__iter__と__next__を実装することで,クラスインスタンスをイテレータとして扱うことができる.
アクセサとセッター,ゲッター
アクセサ: クラス変数にアクセスするための関数.get_NAMEみたいな関数名にすることが一般的.
@property: ゲッター.変数のようにクラス関数にアクセスするためのデコレータ.
@ゲッター名.setter: セッター.変数のようにクラス関数にアクセスするためのデコレータ
[code lang="python"]
class Point:
def __init__(self):
self._x = 0
self._y = 0
def get_x(self):
return self._x
@property
def x(self):
return self._x
@x.setter
def x(self, value):
self._x = value
obj = Point()
print(obj.get_x(), obj.x)
obj.x = 100
print(obj.get_x(), obj.x)
[/code]