
280
第 7 章 データ型とプロトコル
7.8.1
二項演算子
表
7-4
二項演算子
式 メソッド
a + b __add__(self, other)
a - b __sub__(self, other)
a * b __mul__(self, other)
a / b __truediv__(self, other)
a // b __floordiv__(self, other)
a % b __mod__(self, other)
pow(a, b, c), a ** b __pow__(self, other[, modulo])
a << b __lshift__(self, other)
a >> b __rshift__(self, other)
a & b __and__(self, other)
a ^ b __xor__(self, other)
a | b __or__(self, other)
加算(
+
)、減算(
-
)などの、二項演算子で呼び出されます。
other
に指定された値が、演算対
象としてサポートしていないデータの場合には、戻り値として
NotImplemented
を返します。
class Spam:
val = ''
def __add__(self, other):
"""Spam() + 1
などで呼び出される
"""
if isinstance(other, str):
return self.val + other
#
演算できない値なら、
NotImplemented
を返す ...