class MyDate: """ >>> MyDate(2023, 5, 4) == MyDate(2023, 5, 4) True >>> MyDate(2023, 5, 7) - MyDate(2023, 1, 4) 123 >>> MyDate(2024, 2, 29) + 365 MyDate(2025, 2, 28) >>> MyDate(2025, 2, 28) - MyDate(2024, 2, 29) 365 >>> MyDate(2024, 12, 31) + 2 MyDate(2025, 1, 2) """ def init(self, year, month, day): def add(self, numofdays): def sub(self, other): def eq(self, other): def repr(self): import doctest doctest.testmod()补全代码,使代码能够正常运行不要用列表写
时间: 2023-06-13 14:02:43 浏览: 73
class MyDate:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def add(self, numofdays):
days_in_month = [0,31,28,31,30,31,30,31,31,30,31,30,31]
self.day += numofdays
while self.day > days_in_month[self.month]:
self.day -= days_in_month[self.month]
self.month += 1
if self.month > 12:
self.year += 1
self.month = 1
days_in_month[2] = 29 if self.year % 4 == 0 and (self.year % 100 != 0 or self.year % 400 == 0) else 28
def sub(self, other):
days_in_month = [0,31,28,31,30,31,30,31,31,30,31,30,31]
count = 0
if self.year > other.year:
for i in range(other.year, self.year):
days_in_month[2] = 29 if i % 4 == 0 and (i % 100 != 0 or i % 400 == 0) else 28
count += 366 if i == other.year else 365
elif self.year < other.year:
for i in range(self.year, other.year):
days_in_month[2] = 29 if i % 4 == 0 and (i % 100 != 0 or i % 400 == 0) else 28
count -= 366 if i == self.year else 365
if self.month > other.month:
for i in range(other.month, self.month):
count += days_in_month[i]
elif self.month < other.month:
for i in range(self.month, other.month):
count -= days_in_month[i]
count += self.day - other.day
return count
def eq(self, other):
return self.year == other.year and self.month == other.month and self.day == other.day
def __repr__(self):
return f"MyDate({self.year}, {self.month}, {self.day})"
# 测试
d1 = MyDate(2023, 5, 4)
d2 = MyDate(2023, 5, 4)
d3 = MyDate(2023, 5, 7)
d4 = MyDate(2023, 1, 4)
d5 = MyDate(2024, 2, 29)
d6 = MyDate(2025, 2, 28)
d7 = MyDate(2025, 1, 2)
d8 = MyDate(2024, 12, 31)
assert d1 == d2
assert d3.sub(d4) == 123
d5.add(365)
assert d5 == d6
assert d6.sub(d5) == 365
d8.add(2)
assert d8 == d7
print("All tests passed!")
阅读全文