Wednesday, 19 June 2013

Operator overloading in Python

Operator overloading using class rational number .In this allowing classes to define their own behavior with respect to language operators .here is code for
a rational number which add and subtract 

1:  class RationalNumbe:  
2:    def __init__(self, numerator, denominator=1):  
3:      self.n = numerator  
4:      self.d = denominator  
5:    def __add__(self, other):  
6:      if not isinstance(other, RationalNumber):  
7:        other = RationalNumber(other)  
8:      n = self.n * other.d + self.d * other.n  
9:      d = self.d * other.d  
10:      return RationalNumber(n, d)  
11:    def __sub__(self,other):  
12:      if not isinstance(other,RationalNumber):  
13:       other = RationalNumber(other)  
14:      n = self.n * other.d + self.d * other.n  
15:      d = self.d * other.d  
16:      return RationalNumber(n, d)  
17:    def __str__(self):  
18:      return "%s/%s" % (self.n,self.d)  
19:    __rep__ = __str__  
20:  a = RationalNumber(3,2)  
21:  b = RationalNumber(3)  
22:  c=2 
 
23:  print b+c  
24:  print a+b  
25:  print a-b  

In this code we can redefine the existing operator using operator overloading.
that is look at the function add and subtract both function add two rational numbers .Now we can check the output
1:  addition with other 5/1  
2:  addtion 9/2  
3:  subtraction 9/2  

In the output we just get same result for addition and subtraction that is we can redefine existing language operator by class rational numbers

No comments:

Post a Comment