继承 python 日期时间并为使用 super() 的实例添加新属性

Inherit python datetime and add new attribute for the instance in using super()

我想为我自制的classFirstDay的实例添加三个字符串属性,但是在使用super()[=15]的声明时出现错误=]

我的代码:

import datetime


class FirstDay(datetime.datetime):
    def __init__(self, year, month, day):
        super().__init__(year, month, day)
        self.year_str = str(self.year).zfill(4)
        self.month_str = str(self.month).zfill(2)
        self.day_str = str(self.day).zfill(2)

    def __str__(self):
        s = f"FirstDay<{id(self)}> : {self.year_str}-{self.month_str}-{self.day_str}"
        return s


fd = FirstDay(2020, 2, 22)
print(fd)

错误

Traceback (most recent call last):
  File "/home/puff/devWorkspace/SIDE-PROJECT/SoD/main.py", line 22, in <module>
    fd = FirstDay(2020, 2, 22)
  File "/home/puff/devWorkspace/SIDE-PROJECT/SoD/main.py", line 12, in __init__
    super().__init__(year, month, day)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)

实际上 datetimenew 而不是 init

class datetime(date):
    """datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])

    The year, month and day arguments are required. tzinfo may be None, or an
    instance of a tzinfo subclass. The remaining arguments may be ints.
    """
    __slots__ = date.__slots__ + time.__slots__

    def __new__(cls, year, month=None, day=None, hour=0, minute=0, second=0,
                microsecond=0, tzinfo=None, *, fold=0):
        if (isinstance(year, (bytes, str)) and len(year) == 10 and
            1 <= ord(year[2:3])&0x7F <= 12):
            # Pickle support . . .

你可以试试

import datetime


class FirstDay(datetime.datetime):
    def __new__(cls, year, month, day):
        self =  super().__new__(cls, year, month, day)
        self.year_str = str(self.year).zfill(4)
        self.month_str = str(self.month).zfill(2)
        self.day_str = str(self.day).zfill(2)
        
        return self

        
    def __str__(self):
        s = f"FirstDay<{id(self)}> : {self.year_str}-{self.month_str}-{self.day_str}"
        return s


fd = FirstDay(2020, 2, 22)
print(fd)
FirstDay<1995226657456> : 2020-02-22