2024/5/15

所花时间:1小时

代码行:70行

博客量:1篇

了解到的知识点:

# 自定义异常类

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-15 21:12  为20岁努力  阅读(4)  评论(0编辑  收藏  举报