编写类 `MyDate` 具有属性年月日,要求一个构造函数初始化属性年月日,提供重置日期、增加日期(考虑闰年闰月)、输出日期等成员函数。
时间: 2024-05-14 13:14:18 浏览: 61
```python
class MyDate:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def reset_date(self, year, month, day):
self.year = year
self.month = month
self.day = day
def add_day(self, n):
days_in_month = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if self.is_leap_year():
days_in_month[2] = 29
while n > 0:
days_to_end_of_month = days_in_month[self.month] - self.day + 1
if n <= days_to_end_of_month:
self.day += n
break
else:
self.day = 1
self.month += 1
if self.month > 12:
self.month = 1
self.year += 1
n -= days_to_end_of_month
def is_leap_year(self):
if self.year % 400 == 0:
return True
elif self.year % 100 == 0:
return False
elif self.year % 4 == 0:
return True
else:
return False
def output_date(self):
return f"{self.year}-{self.month}-{self.day}"
```
使用方法:
```python
date = MyDate(2022, 2, 28)
print(date.output_date()) # 2022-2-28
date.add_day(1)
print(date.output_date()) # 2022-3-1
date.reset_date(2021, 12, 31)
print(date.output_date()) # 2021-12-31
```
阅读全文