How to subclass datetime?
Jane Austine
janeaustine50 at hotmail.com
Sun Apr 13 12:50:30 EDT 2003
> <posted & mailed>
>
> 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?
>
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'>
>>> z.__str__()
'2003-04-14'
>>> class mydate(datetime.date):
def __str__(self):
return "abc"
>>> z=mydate(2004,4,14)
>>> z
datetime.date(2004, 4, 14)
>>> print z
2004-04-14
>>> z.__str__()
'2004-04-14'
I reckon it is not subclassing the datetime.date class in
its proper definition of subclassing.
>
> > Should I resort to delegation?
>
> Maybe, but it's hard to say unless you can be more specific!
>
>
> Alex
More information about the Python-list
mailing list