datetime objects and __new__()

Peter Otten __peter__ at web.de
Tue Nov 25 10:39:52 EST 2008


peter wrote:

> On Nov 25, 3:46 pm, Peter Otten <__pete... at web.de> wrote:
>> peter wrote:
>> >>>> import datetime
>> >>>> class ts(datetime.datetime):
>> > ...     foo = 'bar'
>> > ...     def __new__(cls, s):
>> > ...         c = super(ts, cls)
>> > ...         return c.fromtimestamp(s)
>> > ...
>> >>>> t = ts(0)
>> > Traceback (most recent call last):
>> > File "<stdin>", line 1, in <module>
>> > File "<stdin>", line 5, in __new__
>> > TypeError: __new__() takes exactly 2 arguments (9 given)
>>
>> > I don't understand why that happens -- am I correct in assuming that
>> > the call to .fromtimestamp() is picking up on the ts class? Shouldn't
>> > it get the datetime class instead?
>>
>> > (Yes, I am aware of the problems of using datetime and timestamps)
>>
>> > Could some kind soul please enlighten me?
>>
>> If the datetime class were implemented in Python the fromtimestamp()
>> method could look like:
>>
>> @classmethod
>> def fromtimestamp(cls, s):
>> year, month, day,... = ...
>> return cls(year, month, day,...)
>>
>> This will fail since you modified the constructor to accept only a single
>> argument.
> 
> Hm, I had hoped that using super() would result in calling the
> constructor of the superclass, ie. datetime. Did I use super() wrong?
> 
> Thanks,
> peter.

Sorry, I didn't pay the necessary attention. 

I've only used super() with "normal" methods, but as

>>> from datetime import *
>>> class TS(datetime):
...     def __new__(cls, ts):
...             return datetime.fromtimestamp(ts)
...
>>> TS(0)
datetime.datetime(1970, 1, 1, 1, 0)

works super() would be the most likely culprit.

Peter




More information about the Python-list mailing list