Why does __init__ not get called?

Rob Conner rtconner at gmail.com
Mon Aug 8 17:12:48 EDT 2005


I'm still working on my DateTime class from last week...
Why does __init__ not get called?

The docs at
http://www.python.org/dev/doc/devel/ref/customization.html
read "If __new__() returns an instance of cls, then the new instance's
__init__() method will be invoked" and as far as I can tell cls is very
much an instance of DateTime

************
import datetime
_datetime = datetime.datetime

class DateTime(_datetime):
    """
    Identical to builtin datetime.datetime, except it accepts
    invalid dates and times as input.
    """
    _valid = True
    __dict__ = _datetime.__dict__

    def __init__(self, year, month, day, *args, **kw):
        print "init called"
        _valid = False
        self.year   = year
        self.month  = month
        self.day    = day
        self.args   = args
        self.kw     = kw

        def throwError():
            raise ValueError, 'Invalid Date'
        for method in _datetime.__dict__.keys():
            if method!='__doc__':
                setattr(self, method, throwError)


    def __new__(cls, year, month, day, *args, **kw):
        print "new called"
        try:
            return _datetime.__new__(cls, year, month, day, *args,
**kw)
        except ValueError:
            return cls
*************




More information about the Python-list mailing list