Issue 1448640: datetime.init cannot be overridden (original) (raw)

Created on 2006-03-13 04:54 by blais, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (5)

msg27768 - (view)

Author: Martin Blais (blais) * (Python committer)

Date: 2006-03-13 04:54

Hi

The following code does not work properly:

#!/usr/bin/env python """ Test overriding constructor of datetime classes. """

import sys, datetime

class MyDate(datetime.date):

def __init__( self, year, month, day ):
    print >> sys.stderr, 'lose data'

d = MyDate(2006, 11, 29) print d

class MyDate(datetime.date):

def __new__( self, year, month, day ):
    print 'lose data'

def __init__( self, year, month, day ):
    print 'lose data again'

d = MyDate(2006, 11, 29) print d

The output is:

lose data 2006-11-29 lose data None

The problem is that the initialization of the object is done in its time_new() method which is registered for new rather than using an init method. This prevent one from overriding the date/datetime/time constructors.

cheers,

msg27769 - (view)

Author: Matt Fleming (splitscreen)

Date: 2006-03-13 15:40

Logged In: YES user_id=1126061

Isn't this an abuse of new ?

Taken from the documentation:

"new must return an object. There's nothing that requires that it return a new object that is an instance of its class argument, although that is the convention. If you return an existing object, the constructor call will still call its init method. If you return an object of a different class, its init method will be called. If you forget to return something, Python will unhelpfully return None, and your caller will probably be very confused."

So, you're actually calling init with None?

Or have i misunderstood?

msg27770 - (view)

Author: Michael Hudson (mwh) (Python committer)

Date: 2006-03-13 16:42

Logged In: YES user_id=6656

datetime.date objects are immutable, so this is the same as not being able to override init in a subclass of int. Override new instead.

msg27771 - (view)

Author: Martin Blais (blais) * (Python committer)

Date: 2006-03-13 21:45

Logged In: YES user_id=10996

Hmmmm... that's not quite true. If I derive from datetime in order to add new data members (e.g. in my case I add "seq" which is used as a sequence number on top of datetime for storing the names of photographs, the sequence number is in case I have a panorama or multiple photographs in burst mode--all within one second), I might want a different constructor.

I tried overriding new and had some troubles, cannot remember what exactly, will reproduce and send code soon.

msg27772 - (view)

Author: Georg Brandl (georg.brandl) * (Python committer)

Date: 2006-03-19 12:25

Logged In: YES user_id=849994

blais: your mistake was that you didn't call datetime.date.new() in your overridden new() and did return None from new whereas new must return a new object of type MyDate.