2024/11/11

class Cexception(Exception):
"""自定义异常处理类"""

def __init__(self, msg):
self.msg = msg


class Date:
"""日期类"""

def __init__(self, year, month, day):
"""有参构造函数,初始化年、月、日"""
try:
if not self._is_valid_date(year, month, day):
raise Cexception("Invalid date!")
self.year = year
self.month = month
self.day = day
except Cexception as e:
print("Error:", e.msg)

def set_date(self, year, month, day):
"""设置日期"""
try:
if not self._is_valid_date(year, month, day):
raise Cexception("Invalid date!")
self.year = year
self.month = month
self.day = day
except Cexception as e:
print("Error:", e.msg)

def display_date(self):
"""以格式 '月/日/年' 输出日期"""
print(f"{self.month}/{self.day}/{self.year}")

def _is_valid_date(self, year, month, day):
"""检查日期是否合法"""
if year < 1 or month < 1 or month > 12 or day < 1:
return False
if month == 2:
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return day <= 29
else:
return day <= 28
if month in {4, 6, 9, 11}:
return day <= 30
return day <= 31


# 测试日期类
if __name__ == "__main__":
# 创建日期对象并设置日期
date1 = Date(2024, 5, 9)
date1.display_date() # 输出:5/9/2024

# 设置无效日期,触发异常处理
date2 = Date(2024, 13, 35) # 输出:Error: Invalid date!

# 设置有效日期
date1.set_date(2024, 2, 29)
date1.display_date() # 输出:2/29/2024

# 设置无效日期,触发异常处理
date1.set_date(2023, 2, 29) # 输出:Error: Invalid date!
posted @ 2024-11-11 23:13  Hbro  阅读(11)  评论(0)    收藏  举报