# Re: How do I learn operator overriding?

Discussion in 'Python' started by python@sarcastic-horse.com, Sep 19, 2003.

1. ### Guest

I forgot to mention some things. If I do subtraction between two qDate
objects, I want to get an integer that shows the number of periods (in
this case, quarters) between the two dates:

>>> 2001q1 = qDate(year=2001, quarter=1)
>>> 2001q4 = qDate(year=2001, quarter=4)
>>> 2001q4 - 2001q1

3

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?

> Hi-
>
>
> I need to make a class for quartlerly dates. I need to be able to compare
> two quarterly dates and get the number of quarters between them. For
> example:
>
>>>> 2001q1 = qDate(year=2001, quarter=1)
>>>> 2001q4 = qDate(year=2001, quarter=4)
>>>> 2001q4 - 2001q1

> 3
>
> 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?
>
> And, on a completely unrelated note, I am getting a truly amazing amount
> of spam today. Anyone else?
>
>
> Thanks for the help.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

, Sep 19, 2003

2. ### Erik Max FrancisGuest

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

Erik Max Francis, Sep 19, 2003