Your class can define special methods with these names
to tell Python how to handle binary operators such as
“*” or “%”. In each case, the calling sequence
will look something like this:
def __method__(self, other):
...
The self argument is the left-hand
operand, and the other argument is the
right-hand operand. Your method will return the result
of the operation.
For each operator, you may supply up to three methods:
The method in the first column performs the normal operation.
The method in the second column is used when the
left-hand operand does not support the given
operation and the operands have different types.
In these methods, self is the
right-hand operand and other is the left-hand operand.
The third column implements the “augmented
assignment” operators such as “+=”. For example, for method __iadd__(self, other), the method must
perform the equivalent of “self +=
other”.
| Operator | Normal | Reversed | Augmented |
|---|---|---|---|
+ | __add__ | __radd__ | __iadd__ |
& | __and__ | __rand__ | __iand__ |
/ | __div__ | __rdiv__ | __idiv__ |
// | __floordiv__ | __rfloordiv__ | __ifloordiv__ |
<< | __lshift__ | __rlshift__ | __ilshift__ |
% | __mod__ | __rmod__ | __imod__ |
* | __mul__ | __rmul__ | __imul__ |
| | __or__ | __ror__ | __ior__ |
** | __pow__ | __rpow__ | __ipow__ |
>> | __rshift__ | __rrshift__ | __irshift__ |
- | __sub__ | __rsub__ | __isub__ |
^ | __xor__ | __rxor__ | __ixor__ |