2

I want to extend the datetime.date class adding it an attribute called status that represents if the date is a work day, an administrative non-work day, courts closed day,...

I've read from How to extend a class in python?, How to extend Python class init and Chain-calling parent constructors in python, but I don't understand it well, so I'm noob with OOP.

>>> import datetime
>>> class Fecha(datetime.date):
        def __init__(self, year, month, day, status):
            super(Fecha, self).__init__(self, year, month, day)
            self.status = status

>>> dia = Fecha(2014, 7, 14, 'laborable')
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    dia = Fecha(2014, 7, 14, 'laborable')
TypeError: function takes at most 3 arguments (4 given)
>>> 
Community
  • 1
  • 1
Trimax
  • 2,413
  • 7
  • 35
  • 59

2 Answers2

6

datetime.date is an immutable type, meaning you need to override the __new__ method instead:

class Fecha(datetime.date):
    def __new__(cls, year, month, day, status):
        instance = super(Fecha, cls).__new__(cls, year, month, day)
        instance.status = status
        return instance

Demo:

>>> import datetime
>>> class Fecha(datetime.date):
...     def __new__(cls, year, month, day, status):
...         instance = super(Fecha, cls).__new__(cls, year, month, day)
...         instance.status = status
...         return instance
... 
>>> dia = Fecha(2014, 7, 14, 'laborable')
>>> dia.status
'laborable'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
-1

problem is in super call

super(Fecha, self).__init__(year, month, day)

Try this.

Nilesh
  • 20,521
  • 16
  • 92
  • 148
  • 1
    This won't work, as there is no `__init__` on an immutable type; it is the `datetime.date.__new__` method that throws the exception here. For mutable types, you'd be correct. – Martijn Pieters Jul 14 '14 at 12:51