How do I learn operator overriding?

luc wastiaux luc at nospam.invalid
Fri Sep 19 15:37:06 EDT 2003


On Fri, 19 Sep 2003 14:25:23 -0400, pytho wrote:

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

in your class:

def __sub__(self, mydate):
    # perform self - mydate
    # and return a new qdate object


I can't reach www.python.org but there should be some documentation on
operator overloading. Also, I recommend the book "learning Python" from
O'reilly ( http://www.oreilly.com/catalog/lpython/ ) which covers most of
the things you need to know about python.

-- 
luc wastiaux
 email: luc-at-4002-dot-org
 jabber: luc at jabber.4002.org





More information about the Python-list mailing list