Extending a class in Python 3 and construct it with __init__
本问题已经有最佳答案,请猛点这里访问。
我想扩展datetime.date类,添加一个名为
我已经读过如何扩展Python中的类了?,如何在python中扩展python类in i t和chain调用父构造函数,但我不太理解,所以我不熟悉oop。
1 2 3 4 5 6 7 8 9 10 11 12 | >>> 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) >>> |
1 2 3 4 5 | 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 |
演示:
1 2 3 4 5 6 7 8 9 10 | >>> 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' |
问题在super call中
1 | super(Fecha, self).__init__(year, month, day) |
试试这个。