View Single Post
  #2 (permalink)  
Old 07-17-2007, 03:10 AM
Gopisoft Gopisoft is offline
D-Web Sr.Programmer
 
Join Date: Feb 2007
Posts: 117
Gopisoft is on a distinguished road
Default Re: Does Python supports Operator Overloading?

Hi,

Operator Overloading in Python
A simple class with operator overloading example in Python.
__add__(self,other) overloads the + symbol when an instance
of addSquare is on the left. __radd_
_ overloads the + symbol
when the instance is on the right. The __add__ method checks
the other object being added, and if it's a string, it
converts it to a floating point. The class adds the squares
of the two objects. (the "__" denotes special methods).

import string
class addSquare:
def __init__(self,value=1):
self.value = value
def __add__(self,other):
if type(other) ==
type("abc"):
other = string.atof(other)
return self.value**2 +
other**2
__radd__ = __add__


-R.Gopi
Reply With Quote