Why can't I subclass datetime.date?

后端 未结 6 1683
半阙折子戏
半阙折子戏 2020-11-29 08:30

Why doesn\'t the following work (Python 2.5.2)?

>>> import datetime
>>> class D(datetime.date):
        def __init__(self, year):
                  


        
6条回答
  •  鱼传尺愫
    2020-11-29 08:54

    Please read the Python reference on Data model, especially about the __new__ special method.

    Excerpt from that page (my italics):

    __new__() is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.

    datetime.datetime is also an immutable type.

    PS If you think that:

    • an object implemented in C cannot be subclassed, or
    • __init__ doesn't get called for C implemented objects, only __new__

    then please try it:

    >>> import array
    >>> array
    
    >>> class A(array.array):
        def __init__(self, *args):
            super(array.array, self).__init__(*args)
            print "init is fine for objects implemented in C"
    
    >>> a=A('c')
    init is fine for objects implemented in C
    >>> 
    

提交回复
热议问题