Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

python - __init__ argument mismatch between super and subclass

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...