Overload divide operator

Overload divide operator

We can implement the following list of method in order to overload add, sub, mul, div operators.

  • __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# from w w w  .  ja v a 2  s . c  om

    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..."

 

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules