Overload Operators
Unary operator
__neg__, -
__pos__, +
__invert__, ~
Binary operator
__add__, +
__sub__, -
__mul__, *
__div__, /
__floordiv__, //
__mod__, %
__pow__, **
__lshift__, <<
__rshift__, >>
__and__, &
__xor__, ^
__or__, |
__iadd__, +=
__isub__, -+
__imul__, *=
__idiv__, /=
__ifloordiv__, //=
__imod__, %=
__ipow__, **=
__ilshift__, <<=
__irshift__, >>=
__iand__, &=
__ixor__, ^=
__ior__, |=
__eq__, ==
__ne__, !=, <>
__gt__, >
__lt__, <
__ge__, >=
__le__, <=
#!/usr/bin/python
class Integer(object):
def __init__(self, value):
self._value = value;
@property
def value(self):
return self._value
@value.setter
def value(self, v):
self._value = v;
@value.deleter
def value(self):
del self._value
def __str__(self):
return "Value: %d" % self._value
def __add__(self, other):
return Integer(self._value + other._value)
def __sub__(self, other):
return Integer(self._value - other._value)
def __mul__(self, other):
return Integer(self._value * other._value)
def __floordiv__(self, other):
return Integer(self._value // other._value)
def __truediv__(self, other):
return Integer(self._value / other._value)
def __neg__(self):
return Integer(-self._value)
def __eq__(self, other):
return (self - other).value == 0
def __lt__(self, other):
return (self - other).value < 0
def __gt__(self, other):
return (self - other).value > 0
def __ne__(self, other):
return not (self == other)
def __iadd__(self, other):
self._value += other._value
return self
def main():
i1 = Integer(10);
i2 = Integer(100);
print(i1+i2) # 110, __add__
print(i1-i2) # -90, __sub__
print(i1*i2) # 1000, __mul__
print(i2/i1) # 10, __truediv__
print(-i1) # -10, __neg__
print(i1 == i2) # False, __eq__
print(i1 < i2) # True, __lt__
print(i1 > i2) # False, __gt__
print(i1 != i2) # True, __ne__
i1 += i2; # __iadd___
print(i1) # 110
if __name__ == '__main__':
main()
Reference