4.14

时长:三个小时

问题:

8-4 【Python0017】设计异常处理类Cexception,并基于异常处理类设计并实现日期类Date
分数 10
作者 doublebest
单位 石家庄铁道大学

【题目描述】定义一个异常类Cexception解决日期类实现中的自定义异常处理。设计的日期类应包含以下内容:

① 有三个成员数据:年、月、日;

② 有设置日期的成员函数;

③ 有用格式"月/日/年"输出日期的成员函数;

④ 要求在日期设置及有参构造函数中添加异常处理。

程序中定义各种日期对象并测试。
【注意事项】闰年的 2 月的天数为 29天,其它年份 2 月28 天;闰年是指:年份能被 4且不能被 100 整除,或者年份能被 400 整除。

注意日期间的关联。
【练习要求】请给出源代码程序和运行测试结果,源代码程序要求添加必要的注释。

代码量:

class CException(Exception):
"""自定义日期相关的异常类"""
def __init__(self, message):
super().__init__(message)

class Date:
def __init__(self, year_input=None, month_input=None, day_input=None):
if year_input is None or month_input is None or day_input is None:
self.prompt_and_set_date()
else:
try:
self.set_year(year_input)
self.set_month(month_input)
self.set_day(day_input)
except CException as e:
print(f"错误:{e}")

def prompt_and_set_date(self):
while True:
try:
year = int(input("请输入年份: "))
month = int(input("请输入月份: "))
day = int(input("请输入日期: "))
self.set_year(year)
self.set_month(month)
self.set_day(day)
break # 成功设置日期后退出循环
except ValueError:
print("输入无效,请确保输入的是整数。")
except CException as e:
print(f"错误:{e}")

def set_year(self, year):
if year < 1:
raise CException("年份不是正整数。")
self.year = year

def set_month(self, month):
if not (1 <= month <= 12):
raise CException("月份错误。")
self.month = month

def set_day(self, day):
if not (1 <= day <= self.get_max_day()):
raise CException("日期范围错误")
self.day = day

def get_max_day(self):
if self.month == 2:
if self.is_leap_year():
return 29
else:
return 28
elif self.month in [4, 6, 9, 11]:
return 30
else:
return 31

def is_leap_year(self):
return (self.year % 4 == 0 and self.year % 100 != 0) or (self.year % 400 == 0)

def display(self):
return f"{self.month}/{self.day}/{self.year}"

# 程序测试 - 通过控制台输入
print("请输入日期(或输入错误的日期以测试异常处理):")
date = Date()
print(f"设置的日期为: {date.display()}")
posted @ 2024-06-19 17:54  孙锺鸣  阅读(1)  评论(0编辑  收藏  举报