5.22

所学时间:2小时

代码行数:100

博客园数:1篇

所学知识:

(四)、设计异常处理Cexception,并基于异常处理类设计并实现日期类Date

题目描述

题目描述

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

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

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

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

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

【源代码程序】

# 自定义异常类

class Cexception(Exception):

    def __init__(self, message):

        self.message = message

 

# 日期类

class Date:

    def __init__(self, year, month, day):

        self.year = year

        self.month = month

        self.day = day

        self.validate_date()

 

    def set_date(self, year, month, day):

        self.year = year

        self.month = month

        self.day = day

        self.validate_date()

 

    def validate_date(self):

        if self.month < 1 or self.month > 12:

            raise Cexception("月份应该在1-12之间")

        if self.day < 1:

            raise Cexception("日期应该为正整数")

        if self.month in [1, 3, 5, 7, 8, 10, 12] and self.day > 31:

            raise Cexception("该月份最多31天")

        if self.month in [4, 6, 9, 11] and self.day > 30:

            raise Cexception("该月份最多30天")

        if self.month == 2:

            if (self.year % 4 == 0 and self.year % 100 != 0) or self.year % 400 == 0:

                if self.day > 29:

                    raise Cexception("闰年2月最多29天")

            else:

                if self.day > 28:

                    raise Cexception("非闰年2月最多28天")

 

    def output_date(self):

        return f"{self.month}/{self.day}/{self.year}"

 

# 测试

try:

    date1 = Date(2024, 2, 30)  # 日期设置异常

except Cexception as e:

    print(f"日期设置异常:{e.message}")

 

try:

    date2 = Date(2023, 2, 29)  # 日期设置异常

except Cexception as e:

    print(f"日期设置异常:{e.message}")

 

date3 = Date(2024, 2, 29)  # 闰年

print(date3.output_date())

 

date4 = Date(2023, 5, 15)  # 非闰年

print(date4.output_date())

posted @ 2024-05-22 17:28  Snor9  阅读(14)  评论(0)    收藏  举报