Subclassing datetime.date

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Feb 7 00:43:26 EST 2010


En Sat, 06 Feb 2010 18:42:29 -0300, John Bokma <john at castleamber.com>  
escribió:

> Sir Wilhelm the Sturdy <wgaggioli at gmail.com> writes:
>>
>> I recently attempted to subclass the datetime.date object resulting in
>> horror and confusion, before submitting to a has-a relationship.
>> That's all fine and dandy, but out of curiosity I'd like to know what
>> I'm missing.
>>
>> class MyDate(datetime.date):
>>
>>     def __init__(self,*args,**kw):
>>        ...

> __init__ is *not* the construction method, __new__ is (at least with new
> style classes)

You're right. But in this case, instead of overriding __new__, I would add  
a separate constructor to avoid confusion with the existing one (a  
classmethod, actually, like fromordinal and fromtimestamp):

py> from datetime import date
py> class date(date):
...   @classmethod
...   def fromDMY(cls, d, m=None, y=None):
...     today = date.today()
...     if m is None: m = today.month
...     if y is None: y = today.year
...     return cls(y, m, d)
...
py> date.fromDMY(20, 3, 2010)
date(2010, 3, 20)
py> date.fromDMY(11)
date(2010, 2, 11)

-- 
Gabriel Genellina




More information about the Python-list mailing list