Does __init__ of subclass need the same argument types as __init__ of base class?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed Mar 25 08:21:04 EDT 2009


Sibylle Koczian a écrit :
(snip)
> 
> I don't understand at all why I get the same message with this little
> script:
> 
> ############################
> import datetime
> 
> class meindatum(datetime.date):
>     def __init__(self, datum):
>         print "meindatum"
>         datetime.date.__init__(self, datum.year, datum.month, datum.day)
> 
> x1 = datetime.date.today()
> print repr(x1)
> x2 = meindatum(x1)
> print repr(x2)
> #######################################
> 
> Executing this from the command line:
> 
> sib at Elend:~> python /windows/E/LinWin/Python/datum_ableiten.py
> datetime.date(2009, 3, 25)
> Traceback (most recent call last):
>   File "/windows/E/LinWin/Python/datum_ableiten.py", line 12, in <module>
>     x2 = meindatum(x1)
> TypeError: an integer is required
> sib at Elend:~>
> 
> The print command inside the __init__ method isn't executed, so that
> method doesn't seem to start at all.

this often happens with (usually C-coded) immutable types. The 
initializer is not called, only the "proper" constructor (__new__). The 
following should work (not tested):

class Meindatum(datetime.date):
    def __new__(self, datum):
         print "meindatum"
         return datetime.date(datum.year, datum.month, datum.day)


HTH




More information about the Python-list mailing list