编写类 `MyDate` 具有属性年月日,要求一个构造函数初始化属性年月日,提供重置日期、增加日期(考虑闰年闰月)、输出日期等成员函数。
时间: 2024-05-08 21:17:17 浏览: 7
```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 is_leap_year(self, year):
return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
def add_date(self, days):
month_day = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if self.is_leap_year(self.year):
month_day[2] = 29
while days > 0:
if days >= month_day[self.month] - self.day + 1:
days -= month_day[self.month] - self.day + 1
self.month += 1
if self.month > 12:
self.year += 1
self.month = 1
if self.is_leap_year(self.year):
month_day[2] = 29
else:
month_day[2] = 28
self.day = 1
else:
self.day += days
days = 0
def output_date(self):
print("{0:04d}-{1:02d}-{2:02d}".format(self.year, self.month, self.day))
```
其中,`__init__` 方法用于初始化年月日属性;`reset_date` 方法用于重置日期;`is_leap_year` 方法用于判断是否为闰年;`add_date` 方法用于增加日期,考虑闰年闰月;`output_date` 方法用于输出日期。