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

Sibylle Koczian nulla.epistola at web.de
Wed Mar 25 11:21:49 EDT 2009


Bruno Desthuilliers schrieb:
> Sibylle Koczian a écrit :
> (snip)
>>
>>
>> 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)
> 

Thank you, that works, and I learned something (didn't know how Python
objects are created). After some trial, error and searching on the
Python website I found how to give Meindatum additional data attributes.
Now it looks like this:

class Sonderdatum(datetime.date):
    """
    Date with additional attribute (integer)
    """
    def __new__(cls, datum):
        print "Hier Sonderdatum.__new__"
        (x, y, z) = (datum.year, datum.month, datum.day)
        print "Jahr: %d, Monat: %d, Tag: %d" % (x, y, z)
        return super(Sonderdatum, cls).__new__(cls, datum.year,
                                               datum.month,
                                               datum.day)

    def __init__(self, datum, sonder=0):
        print "Hier Sonderdatum.__init__"
        # superclass __init__ is _not_ called!
	# super(Sonderdatum, self).__init__(x, y, z)
        self.sonder = sonder

def testeSondertage():
    datum = datetime.datetime.strptime("01.01.2009", "%x")
    print repr(datum.date())
    xx = Sonderdatum(datum.date())
    print xx.year, xx.month, xx.day, xx.sonder

if __name__ == "__main__":
    locale.setlocale(locale.LC_ALL, '')
    testeSondertage()

And now I'll put this into something remotely useful.

Je vous prie d'agréer mes meilleurs salutations,
Sibylle



More information about the Python-list mailing list