日期类使用三个整数记录年、月、日,其中月份的取值范围为1-12,日期的取值范围为1-31,尝试写出该类的构造函数,接受三个整数作为年月日的值,并验证月份和日期的有效性,当给出的日期数据无效时抛出自定义的日期范
时间: 2024-02-09 22:12:52 浏览: 17
围异常。
以下是该类的构造函数的实现:
```python
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
if not self._is_valid():
raise DateRangeError(f"Invalid date: {year}-{month}-{day}")
def _is_valid(self):
if self.month < 1 or self.month > 12:
return False
if self.day < 1 or self.day > 31:
return False
if self.month == 2 and self.day > 29:
return False
if self.month in [4, 6, 9, 11] and self.day > 30:
return False
if self.month == 2 and self.day == 29 and (self.year % 4 != 0 or (self.year % 100 == 0 and self.year % 400 != 0)):
return False
return True
class DateRangeError(Exception):
pass
```
该构造函数会首先将年、月、日的值存储为对象的属性。然后调用 _is_valid() 方法验证月份和日期的有效性。如果日期无效,就会抛出自定义的日期范围异常(DateRangeError)。
_is_valid() 方法会根据公历的规则验证日期的有效性。它会检查月份和日期是否在规定的取值范围内,以及特殊情况下(如闰年)是否符合要求。如果日期无效,就会返回 False;否则返回 True。