从 class (datetime.date) 继承会导致 super().__init__(...) 参数过多 TypeError

Inheriting from a class (datetime.date) causes a super().__init__(...) too many arguments TypeError

我正在使用 Python 3.6 并想编写一个 class 来扩展 datatime.date 并在我的代码中引入一些我需要的额外属性和方法。 问题是由于似乎参数太多,初始化似乎无法正常工作。

以下是精简的代码:

FORMAT__DD_MM_YYYY = "dd.mm.yyyy"
from datetime import date


class DateExtended(date):
    date_string = None
    date_format = None

    def __init__(self, year: int, month: int, day: int, date_format: str=None):
        super().__init__(year=year, month=month, day=day)
        self.date_format = date_format
        self.date_string = "{:02d}.{:02d}.{:04d}".format(self.day, self.month, self.year)

bla1 = DateExtended(year=2010, month=5, day=3, date_format=FORMAT__DD_MM_YYYY_DOT)

执行它会导致以下错误:

bla1 = DateExtended(year=2010, month=5, day=3, date_format=FORMAT__DD_MM_YYYY_DOT)
TypeError: function takes at most 3 arguments (4 given)

我在这里做错了什么,应该如何解决?

是不是因为date没有延伸object


旁注:当我自己尝试解决这个问题时,我还编写了一个不同的 class,它不继承自 date,只是创建一个 date 对象并存储它作为其属性之一:

self.date = date(year=year, month=month, day=day)

没有遇到任何问题。

这是因为 datetime.date__new__ 中进行了初始化,而不是在 __init__ 中进行了初始化,错误来自于 datetime.date.__new__ 只接受 3 个参数,而不是 4 个。

因此您还必须覆盖 __new__

FORMAT__DD_MM_YYYY = "dd.mm.yyyy"
from datetime import date


class DateExtended(date):
    date_string = None
    date_format = None

    def __new__(cls, year: int, month: int, day: int, date_format: str=None):
        # because __new__ creates the instance you need to pass the arguments
        # to the superclass here and **not** in the __init__
        return super().__new__(cls, year=year, month=month, day=day)

    def __init__(self, year: int, month: int, day: int, date_format: str=None):
        # datetime.date.__init__ is just object.__init__ so it takes no arguments.
        super().__init__()  
        self.date_format = date_format
        self.date_string = "{:02d}.{:02d}.{:04d}".format(self.day, self.month, self.year)

bla1 = DateExtended(year=2010, month=5, day=3, date_format=FORMAT__DD_MM_YYYY)