Search code examples
pythoninheritancesuperpython-datetime

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


I want to add three string attribute for the instance of my self-made class FirstDay, but I got an error when I using the declaration of super()

My code:

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)

Error

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)

Solution

  • Actually datetime has new not 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 . . .
    

    You can try

    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