overloading operators
Gustavo Córdova Avila
gcordova at sismex.com
Wed Jan 23 18:37:12 EST 2002
>
> Hello
>
> Is it possible to overload an operator in python (for objects) ?
>
yes.
class ArrayLikeThingy:
def __init__(self, min, max):
self.min = min
self.max = max
def __getitem__(self, key):
"return the square of the index "
"as long as it's between min and max."
if self.min <= key <= self.max:
return key*key
raise IndexError("Outside the range (%d,%d)" % (self.min,self.max)
ob = ArrayLikeThingy(1,10)
ob[1] = 1
ob[2] = 4
ob[3] = 9
...
ob[9] = 81
ob[10] = 100
ob[11] -> IndexError
and you can overload other functions, like:
__setitem__(self, key, value)
__add__(self, value)
__mult__(self, value)
__str__(self)
__getattr__(self,attr)
etc etc.
Check the manual under "operators", I believe.
-gus
More information about the Python-list
mailing list