The following methods can be defined to emulate numeric objects. Methods corresponding to operations that are not supported by the particular kind of number implemented (e.g., bitwise operations for non-integral numbers) should be left undefined.
+
,
-
, *
, /
, %
,
divmod() ,
pow() , **
, <
<
,
>
>
, &
, ^
, |
). For instance, to
evaluate the expression x+
y, where x is an
instance of a class that has an __add__() method,
x.__add__(y)
is called. Note that
__pow__() should be defined to accept an optional third
argument if the ternary version of the built-in
pow() function is to be supported.
+
,
-
, *
, /
, %
,
divmod() ,
pow() , **
, <
<
,
>
>
, &
, ^
, |
) with reflected
(swapped) operands. These functions are only called if the left
operand does not support the corresponding operation. For instance,
to evaluate the expression x-
y, where y is an
instance of a class that has an __rsub__() method,
y.__rsub__(x)
is called. Note that ternary
pow() will not try calling
__rpow__() (the coercion rules would become too
complicated).
+=
, -=
, *=
, /=
, %=
,
**=
, <
<=
, >
>=
, &=
,
=
, |=
). These methods should attempt to do the
operation in-place (modifying self) and return the result (which
could be, but does not have to be, self). If a specific method
is not defined, the augmented operation falls back to the normal
methods. For instance, to evaluate the expression
x+=
y, where x is an instance of a class that
has an __iadd__() method, x.__iadd__(y)
is
called. If x is an instance of a class that does not define a
__iadd() method, x.__add__(y)
and
y.__radd__(x)
are considered, as with the
evaluation of x+
y.
-
,
+
, abs() and ~
).
None
if conversion is impossible. When
the common type would be the type of other
, it is sufficient to
return None
, since the interpreter will also ask the other
object to attempt a coercion (but sometimes, if the implementation of
the other type cannot be changed, it is useful to do the conversion to
the other type here).
Coercion rules: to evaluate x op y, the
following steps are taken (where __op__() and
__rop__() are the method names corresponding to
op, e.g., if op is `+
', __add__() and
__radd__() are used). If an exception occurs at any point,
the evaluation is abandoned and exception handling takes over.
x.__coerce__(y)
; skip to step 2 if the
coercion returns None
.
x.__op__(y)
; otherwise, restore x and
y to their value before step 1a.
y.__coerce__(x)
; skip to step 3 if the
coercion returns None
.
y.__rop__(x)
; otherwise,
restore x and y to their value before step 2a.
+
' and x is a
sequence, sequence concatenation is invoked.
*
' and one operand is a
sequence and the other an integer, sequence repetition is
invoked.