Operator overloading


In [1]:
from __future__ import division

class AlienInt(object):
    def __init__(self, value):
        self.value = value
    
    def __add__(self, other):
        if isinstance(other, AlienInt):
            return AlienInt(self.value + other.value - 1)
        else:
            raise TypeError("Can not add AlienInt to " + type(other).__name__)
            
    def __sub__(self, other):
        if isinstance(other, AlienInt):
            return AlienInt(self.value - other.value - 1)
        else:
            raise TypeError("Can not subtract " + type(other).__name__ + " from AlienInt")
    
    def __mul__(self, other):
        if isinstance(other, AlienInt):
            return AlienInt(self.value*other.value - 1)
        else:
            raise TypeError("Can not multiply " + type(other).__name__ + " to AlientInt")
            
    def __floordiv__(self, other):
        if isinstance(other, AlienInt):
            return AlienInt(self.value//other.value - 1)
        else:
            raise TypeError("Can not divide AlienInt by " + type(other).__name__)

    def __truediv__(self, other):
        if isinstance(other, AlienInt):
            return self.__floordiv__(other)
        else:
            raise TypeError("Can not divide AlienInt by " + type(other).__name__)        

    def __str__(self):
        return str(self.value)
    
    def __repr__(self):
        return repr(self.value)

In [2]:
a = AlienInt(10);
b = AlienInt(5);
a + b


Out[2]:
14

In [3]:
a - b


Out[3]:
4

In [4]:
a*b


Out[4]:
49

In [5]:
a/b


Out[5]:
1

Overloading Comparison Operators


In [6]:
from __future__ import division

class AlienInt(object):
    def __init__(self, value):
        self.value = value
    
    def __eq__(self, other):
        return self.value == other.value
            
    def __ne__(self, other):
        return not self.__eq__(other)
                   
    def __lt__(self, other):
        return self.value < other.value
    
    def __gt__(self, other):
        return self.value > other.value
    
    def __le__(self, other):
        return self.value <= other.value
    
    def __ge__(self, other):
        return self.value >= other.value
            
    def __str__(self):
        return str(self.value)
    
    def __repr__(self):
        return repr(self.value)

In [7]:
a = AlienInt(5);
b = AlienInt(5);
a == b


Out[7]:
True

In [8]:
a != b


Out[8]:
False

In [9]:
c = AlienInt(10);
d = AlienInt(5);
c < d


Out[9]:
False

In [10]:
c > d


Out[10]:
True

Example : Rational Number


In [11]:
class Rational:
    """
    This class allows operations of rational number on its objects
    """
    def __init__(self, num, den=1):
        if(den == 0):
            raise ValueError("0 is not allowed in denominator")
        self.num = num
        self.den = den

    def __str__(self):
        if self.num == 0:
            return '0'
        return str(self.num) + "/" + str(self.den)
    
    def __repr__(self):
        if self.num == 0:
            return '0'
        return repr(self.num) + "/" + repr(self.den)

    def __add__(self,other):
        if not isinstance(other, Rational):
            other = Rational(other)
        new = Rational((self.num*other.den + self.den*other.num), self.den*other.den)
        return new

    def __sub__(self,other):
        if not isinstance(other, Rational):
            other = Rational(other)
        new = Rational((self.num*other.den - self.den*other.num), self.den*other.den)
        return new

    def __mul__(self,other):
        if not isinstance(other, Rational):
            other = Rational(other)
        new = Rational((self.num*other.num), self.den*other.den)
        return new

    def __truediv__(self, other):
        if not isinstance(other, Rational):
            other = Rational(other)
        new = Rational(self.num*other.den, self.den*other.num)
        return new

In [12]:
p = Rational(10, 15)
q = Rational(2, 3)
p + q


Out[12]:
60/45

In [13]:
p - q


Out[13]:
0

In [14]:
p*q


Out[14]:
20/45

In [15]:
p / q


Out[15]:
30/30

Excercise

Write a simplify method for this Rational number which should represent it in simplified form of fraction


In [16]:
class Rational:
    """
    This class allows operations of rational number on its objects
    """
    def __init__(self, num, den=1):
        if(den == 0):
            raise ValueError("0 is not allowed in denominator")
        self.num = num
        self.den = den
        self.simplify()

    def __str__(self):
        if self.num == 0:
            return '0'
        return str(self.num) + "/" + str(self.den)
    
    def __repr__(self):
        if self.num == 0:
            return '0'
        return repr(self.num) + "/" + repr(self.den)

    def __add__(self,other):
        if not isinstance(other, Rational):
            other = Rational(other)
        new = Rational((self.num*other.den + self.den*other.num), self.den*other.den)
        return new

    def __sub__(self,other):
        if not isinstance(other, Rational):
            other = Rational(other)
        new = Rational((self.num*other.den - self.den*other.num), self.den*other.den)
        return new

    def __mul__(self,other):
        if not isinstance(other, Rational):
            other = Rational(other)
        new = Rational((self.num*other.num), self.den*other.den)
        return new

    def __truediv__(self, other):
        if not isinstance(other, Rational):
            other = Rational(other)
        new = Rational(self.num*other.den, self.den*other.num)
        return new

    def simplify(self):
        while(True):
            gcd = self.getGCD(self.num, self.den)
            if gcd == self.num or gcd == self.den or gcd ==1:
                self.num //= gcd
                self.den //= gcd

    def getGCD(self,a,b):
        maxm = max(a,b)
        minm  = min(a,b)
        if maxm%minm == 0:
            return minm
        else:
            rem = maxm%minm
            return self.getGCD(minm,rem)

In [17]:
p = Rational(10, 15)
q = Rational(2, 3)
p + q


Out[17]:
4/3

In [18]:
p * q


Out[18]:
4/9

Error Handling


In [19]:
try:
    a = 1/0
except Exception:
    print "not possible"
finally:
    print "You tried to divide"


not possible
You tried to divide