TypeError with date class

Cédric Lucantis omer at no-log.org
Fri Jun 13 11:27:54 EDT 2008


Hi,

Le Friday 13 June 2008 15:24:31 Dummy Pythonese Luser, vous avez écrit :
> Greetings *.*:
>
> The following program caused an error and puzzled me to no end. Any help
> immensely appreciated.
>
>
> class Second(First):
>   def __init__(self, datestr):
>     y = int(datestr[0:4])
>     m = int(datestr[4:6])
>     d = int(datestr[6:8])
>     First.__init__(self, y, m, d)
>
> #     a = Second("20060201")
> # TypeError: function takes exactly 3 arguments (1 given)
> # Why?

probably because date is an immutable type, so the init stuff is done in 
__new__ and not __init__ (and thus __new__ expects the same args as 
__init__). So you should replace First and Second __init__ methods by 
something like this :


def __new__ (cls, datestr):
     y = int(datestr[0:4])
     m = int(datestr[4:6])
     d = int(datestr[6:8])
     self = date.__new__(cls, y, m, d)
     return self


The general rule is to do your initialization in __new__ for immutable types 
and in __init__ for mutable ones. See the chapter 3 of the reference manual 
(data model) for more infos.

-- 
Cédric Lucantis



More information about the Python-list mailing list