4.22
所花时间:4小时
代码量:43
博客篇:1
python
设计异常处理类Cexception,并基于异常处理类设计并实现日期类Date
【题目描述】
【题目描述】
定义一个异常类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()
设计并实现平面点类Point
【题目描述】
定义一个平面点类Point,对其重载运算符关系运算符,关系运算以距离坐标原点的远近作为基准,远的为大。程序完成对其的测试。
【源代码程序】
import math class Point(): def __init__(self,x,y): self.x = x self.y = y def __lt__(self, other): l1 = math.sqrt(self.x**2+self.y**2) l2 = math.sqrt(other.x**2+other.y**2) return l1<l2 def __le__(self, other): l1 = math.sqrt(self.x**2+self.y**2) l2 = math.sqrt(other.x**2+other.y**2) return l1<=l2 def __gt__(self, other): l1 = math.sqrt(self.x**2+self.y**2) l2 = math.sqrt(other.x**2+other.y**2) return l1>l2 def __ge__(self, other): l1 = math.sqrt(self.x**2+self.y**2) l2 = math.sqrt(other.x**2+other.y**2) return l1>=l2 def __eq__(self, other): l1 = math.sqrt(self.x**2+self.y**2) l2 = math.sqrt(other.x**2+other.y**2) return l1==l2 def __ne__(self, other): l1 = math.sqrt(self.x**2+self.y**2) l2 = math.sqrt(other.x**2+other.y**2) return l1!=l2 p1 = Point(1,2) p2 = Point(3,4) p=p1<p2 print(p) p=p1<=p2 print(p) p=p1>p2 print(p) p=p1>=p2 print(p) p=p1==p2 print(p) p=p1!=p2 print(p)

浙公网安备 33010602011771号