python编写一个日期类
时间: 2023-09-17 11:13:07 浏览: 38
下面是一个简单的 Python 日期类的示例:
```python
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def is_valid_date(self):
if self.year < 1 or self.month < 1 or self.month > 12 or self.day < 1:
return False
if self.month == 2:
if self.year % 4 == 0 and (self.year % 100 != 0 or self.year % 400 == 0):
return self.day <= 29
else:
return self.day <= 28
elif self.month in [4, 6, 9, 11]:
return self.day <= 30
else:
return self.day <= 31
def __str__(self):
return f"{self.year}-{self.month}-{self.day}"
```
该类有三个属性:year、month、day,表示年份、月份和日期。`__init__` 方法用于初始化这些属性。`is_valid_date` 方法用于检查日期是否有效,例如,2 月份的日期不能超过 29 天(闰年)或 28 天(平年)。`__str__` 方法用于将日期以字符串形式返回。
下面是一个使用该类的示例:
```python
d = Date(2021, 2, 29)
if d.is_valid_date():
print(d)
else:
print("Invalid date")
```
输出:
```
Invalid date
```