我想为我自制类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)
其实datetime
有new
没有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