0

I'm trying to make a class inherit from datetime.date, call the superclasses __init__ function, and then add a few variables on top which involves using a fourth __init__ argument on top of year, month and day.

Here is the code:

class sub_class(datetime.date):    
    def __init__(self, year, month, day, lst):  
        super().__init__(year, month, day)
            for x in lst:
                # do stuff

inst = sub_class(2014, 2, 4, [1,2,3,4])

This raises the below error:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    inst = sub_class(2014, 2, 4, [1,2,3,4])
TypeError: function takes at most 3 arguments (4 given)

If I remove the last argument I get the below:

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    inst = sub_class(2014, 2, 4)
TypeError: __init__() missing 1 required positional argument: 'lst'

I take it that this is due to a mismatch between __new__ and __init__. But how do I solve it? Do I need to redefine __new__? In which case do I need to call the superclasses __new__ constructor as well?

NDevox
  • 4,056
  • 4
  • 21
  • 36

1 Answers1

1

Yes, you need to implement __new__, and call it on the super-class; for example:

class sub_class(datetime.date):

    def __new__(cls, year, month, day, lst):
        inst = super(sub_class, cls).__new__(cls, year, month, day)
        inst.lst = lst
        return inst

In use:

>>> s = sub_class(2013, 2, 3, [1, 2, 3])
>>> s
sub_class(2013, 2, 3)  # note that the repr isn't correct 
>>> s.lst
[1, 2, 3]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Thanks, I've never been 100% on the difference between `__init__ and `__new__`. I'm assuming I can not bother with an `__init__` function and do everything I would have done in init in `__new__ `? – NDevox Feb 04 '15 at 22:22
  • 1
    That's correct, there's no need for an `__init__` in this case - just assign attributes to `inst` (not sure if there's a conventional name for that...) instead of `self`. For more information, see e.g. http://stackoverflow.com/q/674304/3001761 – jonrsharpe Feb 04 '15 at 22:25