[Tutor] funny behaviour

Kent Johnson kent37 at tds.net
Mon Mar 14 11:58:12 CET 2005


Jacob Abraham wrote:
> Dear Tutors,
> 
>    A class was created to extend timedelta to add and
> subtract months. Simple doctests that simply create an
> instance of the class failed. Could someone please
> explain this really funny behaviour.

timedelta is an immutable class (its instances have fixed values that can't be changed). When you 
subclass an immutable class you have to override __new__ instead of __init__. See this link for 
details and examples:
http://www.python.org/2.2.3/descrintro.html#__new__

Kent

> 
> Regards,
> Jacob Abraham
> 
> from datetime import datetime, timedelta
> 
> class WeirdTimeDelta(timedelta):
>     """Allows addition and subtraction of months.
> 
>     Variables are getting passed to the timedelta
> constructor ??
> 
>     >>> delta = WeirdTimeDelta(5)
>     >>> delta.days
>     0
> 
>     Should'nt this work ???
> 
>     >>> delta = WeirdTimeDelta(months=5)
> 
>     """
> 
>     def __init__(self, months=0, *vals, **kwds):
>         """Constructs a weird time delta."""
>         super(WeirdTimeDelta, self).__init__(*vals,
> **kwds)
>         self.months = months
> 
> if __name__ == "__main__":
>     import doctest
>     doctest.testmod()
> 
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around 
> http://mail.yahoo.com 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 




More information about the Tutor mailing list