python实验5

题目描述】

题目描述】

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

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

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

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

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

【源代码程序】

class Cexception :

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

        if Cexception.judge(year,month,day) :

            self.year = year

            self.month = month

            self.day = day

        else:

            self.year = -1

            self.month = -1

            self.day = -1

            print("日期有误")

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

        if Cexception.judge(year,month,day) :

            self.year = year

            self.month = month

            self.day = day

        else:

            self.year = -1

            self.month = -1

            self.day = -1

            print("日期有误")

    def display(self):

        if self.month ==-1 or  self.year == -1 or self.day == -1:

            print("",end="")

        else:

            print(str(self.month)+"/"+str(self.day)+"/"+str(self.year))

    def judge(year,month,day):

        leap = False

        legal = False

        if year>0:

            if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:

                leap = True

            if month in [1, 3, 5, 7, 8, 10, 12]:

                if 1 <= day <= 31:

                    legal = True

            elif month in [4, 6, 9, 11]:

                if 1 <= day <= 30:

                    legal = True

            elif month == 2:

                if not leap and 1 <= day <= 28:

                    legal = True

                elif leap and 1 <= day <= 29:

                    legal = True

        else:

            legal = False

        return legal

 

c = Cexception(-1,11,2)

c.display()

c = Cexception(2019,11,2)

c.display()

c = Cexception(2019,2,29)

c.display()

c = Cexception(2020,2,29)

c.display()

posted @ 2024-06-19 21:17  vvvcutee  阅读(1)  评论(0编辑  收藏  举报