Reputation: 4086
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?
Upvotes: 0
Views: 229
Reputation: 121975
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]
Upvotes: 1