Why can't I subclass datetime.date?

后端 未结 6 1673
半阙折子戏
半阙折子戏 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:50

    Regarding several other answers, this doesn't have anything to do with dates being implemented in C per se. The __init__ method does nothing because they are immutable objects, therefore the constructor (__new__) should do all the work. You would see the same behavior subclassing int, str, etc.

    >>> import datetime
    >>> class D(datetime.date):
            def __new__(cls, year):
                return datetime.date.__new__(cls, year, 1, 1)
    
    
    >>> D(2008)
    D(2008, 1, 1)
    

提交回复
热议问题