Why can't I subclass datetime.date?

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

    You can wrap it and add extended functionality to your wrapper.

    Here is an example:

    class D2(object):
        def __init__(self, *args, **kwargs):
            self.date_object = datetime.date(*args, **kwargs)
    
        def __getattr__(self, name):
            return getattr(self.date_object, name)
    

    And here is how it works:

    >>> d = D2(2005, 10, 20)
    >>> d.weekday()
    3
    >>> dir(d)
    ['__class__', '__delattr__', '__dict__', '__doc__', '__getattr__',
     '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
     '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__',
     '__weakref__', 'date_object']
    >>> d.strftime('%d.%m.%Y')
    '20.10.2005'
    >>>
    

    Note that dir() doesn't list datetime.dates attributes.

提交回复
热议问题