
282
第 7 章 データ型とプロトコル
ret.val = self.val * -1
return ret
7.8.3
比較演算子
表
7-7
比較演算子
式 メソッド
a < b __lt__(self, other)
a <= b __le__(self, other)
a == b __eq__(self, other)
a != b __ne__(self, other)
a > b __gt__(self, other)
a >= b __ge__(self, other)
比較演算子で呼び出され、それぞれサポートする演算子を実装します。
other
に、演算をサポー
トしていない引数を指定された場合は、戻り値を
NotImplemented
とします。
この比較演算メソッドは「拡張比較(
rich comparison
)」と呼ばれていますが、
Python3
以降で
は、古い比較メソッド
__cmp__()
が削除され、現在では拡張比較だけが存在します。
class Spam:
def __lt__(self, other):
"""
比較演算子
<
の実装
get_value()
メソッドの結果を比較する
"""
if hasattr(other, 'get_value'):
return self.get_value() < other.get_value()
return NotImplemented
...
比較演算子は算術演算子と異なり、演算子の左項がその演算子をサポートしないときに呼び出さ
れる、
__r ...