How do I learn operator overriding?
Erik Max Francis
max at alcyone.com
Fri Sep 19 15:41:55 EDT 2003
python at sarcastic-horse.com wrote:
> The only problem is that I have no idea how to override operators in
> python. Can anyone give me a few trivial examples of how it is done?
Just override the __sub__ method:
>>> class Date:
... def __init__(self, year, quarter):
... self.year = year
... self.quarter = quarter
... def quarters(self):
... return self.year*4 + self.quarter
... def __sub__(self, other):
... return self.quarters() - other.quarters()
...
>>> Date
<class __main__.Date at 0x402e053c>
>>> q1 = Date(2001, 1)
>>> q4 = Date(2001, 4)
>>> q4 - q1
3
> And, on a completely unrelated note, I am getting a truly amazing
> amount
> of spam today. Anyone else?
Yep. I've gotten 262 MB since 2 am this morning. Another worm is out
and about, I'd presume.
--
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ You and I / We've seen it all / Chasing our hearts' desire
\__/ The Russian and Florence, _Chess_
More information about the Python-list
mailing list