Operator Overloading: add, sub, mul, div : Operator Overloading « Class « Python Tutorial






__add__ : Implements the plus "+" operator.
__sub__ : Implements the minus "-" operator.
__mul__ : Implements the multiplication "*" operator.
__div__ : Implements the division "/" operator.


class Double(object) :
    def __init__(self) :
        self.value = 0

    def __add__(self, value) :
        return self.value + 2 * value

    def __sub__(self, value) :
        return self.value - 2 * value

    def __mul__(self, value) :
        return self.value * (2*value)

    def __div__(self, value) :
        return self.value / (2*value)

    def __cmp__(self, value) :
        if self.value < (value*2) :
            return -1
        elif self.value == value*2 :
            return 0
        else :
            return 1

d = Double()
d.value = 10

print d + 2
print d - 2
print d * 2
print d / 1

if d < 5 : print "Less than 5"
else : print "Not less than 5"

d.value = 10
if d == 5 :
       print "Yes!"
else :
       print "no..."








11.5.Operator Overloading
11.5.1.Operator Overloading: add, sub, mul, div
11.5.2.Operator Overloading: sub
11.5.3.Classes Can Intercept Python Operators