繁体   English   中英

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

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

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

我的代码:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM