How to subclass datetime?
Alex Martelli
aleax at aleax.it
Sun Apr 13 16:17:21 EDT 2003
Jane Austine wrote:
>> > Running Python 2.3a2 on win XP.
>> >
>> > I'm interested in the new datetime module and I want to subclass
>> > date/datetime class to modify the behaviour. However, simply
>> > inheritting the classes(like "class mydate(date):" ) didn't work.
>>
>> Please define "didn't work"...:
>>
>> >>> import datetime
>> >>> class mydate(datetime.date):
>> ... pass
>> ...
>> >>> xx=mydate(2003,4,14)
>> >>> print xx
>> 2003-04-14
>> >>>
>>
>> Seems to be working just fine. What exactly isn't working for you?
"seems" is the key word here -- behind the covers, weird things are
indeed happening;-). Sorry for not looking into it a bit deeper in
the first place, but the generic "didn't work" indication wasn't
very encouraging to do so;-).
> For example,
>
>>>> class mydate(datetime.date):
> def abc(self):
> print "abc"
>
>
>>>> z=mydate(2003,4,14)
>>>> z.abc()
> Traceback (most recent call last):
> File "<pyshell#6>", line 1, in -toplevel-
> z.abc()
> AttributeError: 'datetime.date' object has no attribute 'abc'
>>>> type(z)
> <type 'datetime.date'>
VERY interesting. It seems to boil down to function date_new in
module datetimemodule.c -- i.e., in Python terms, date.__new__ --
it ignores the PyTypeObject it's passed, and generates an object
of the SPECIFIC type PyDateTime_DateType no matter what.
I think it can be stated that you've found a bug, one way or
another -- if the design intent is that the type cannot be
subclassed, then the type shouldn't have the Py_TPFLAGS_BASETYPE
flag set (which it does), so the attempt at subclassing it would
immediately give a clear error message; if subclassing is meant
to be allowed, then date.__new__ should work more canonically...
I suggest you submit the bug report to sourceforge -- that's what
alpha releases are for, after all.
Alex
More information about the Python-list
mailing list