How do I learn operator overriding?

Erik Max Francis max at alcyone.com
Fri Sep 19 15:44:19 EDT 2003


python at sarcastic-horse.com wrote:

> But if I subtract an integer from my qDate object, I want to get a new
> qDate object returned, like this:
> 
> >>> 2001q4 - 2
> (new qDate object with year=2001 and quarter=2)
> 
> Any ideas how to make this possible?

In that case an extra class might be appropriate (untested):

	class SubordinateDate(Date):
	    def __init__(self, date, quarter):
	        self.year = date.year
	        self.quarter = quarter

and change the original Date.__sub__ method to:

	...
	    def __sub__(self, other):
	        if type(other) is types.IntType:
	            other = SubordinateDate(date, other)
	        return self.quarters() - other.quarters()
	...

-- 
   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