1. 使用组合创建一个圆环类(组合:一个类的对象可能是别的类的属性)
from math import pi class Circle(): def __init__(self,r): self.r=r def area(self): return pi*self.r**2 def perimeter(self): return 2*pi*self.r class Ring(): def __init__(self,outside,inside): # 这里面的outside,inside其实是Circle实例化的对象,在Ring类中作为了Ring类对象的属性,也就是组合类型 self.outside=outside self.inside=inside def area(self): return self.outside.area()-self.inside.area() def perimeter(self): return self.outside.perimeter()+self.inside.perimeter() outside=Circle(4) # 实例化Circle 就是代表一个圆(对象),该对象又是作为Ring的属性的 inside=Circle(3) print(Ring(outside,inside).area()) # 计算圆环的面积 print(Ring(outside,inside).perimeter())
运行结果:
2. ,使用组合创建一个老师类,老师可以有很多属性,然后需要有生日(也得是一个类),也可以有其他类,或者属性(主要是跟老师相关)
import time class Birthday(): def __init__(self,year,mon,day): self.year=year self.mon=mon self.day=day def view(self): return "生日为:%s年%s月-%s日"%(self.year,self.mon,self.day) class Days(): def __init__(self,year,mon,day): # 这个year是当前的 self.year=year self.mon=mon self.day=day def cal_days(self): days=0 if self.year %4==0 and self.year%100!=0 or self.year%400==0: # 闰年 L=[31,29,31,30,31,30,31,31,30,31,30,31] else: L=[31,28,31,30,31,30,31,31,30,31,30,31] if self.mon==1: return self.day else: for i in range(self.mon-1): days+=L[i] return days class Teacher(): def __init__(self,name,age,sex,birthday,days_bir): self.name=name self.age=age self.sex=sex self.birthday=birthday self.days_bir=days_bir def view_info(self): return "今天是:%s月%s日,老师生日是:%s"%(time.localtime().tm_mon,time.localtime().tm_mday,self.birthday.view()) def cal_days_dif(self,days_cur): if self.days_bir.cal_days()-days_cur.cal_days()>=0: return self.days_bir.cal_days()-days_cur.cal_days() else: return days_cur.cal_days()-self.days_bir.cal_days()+365 birthday=Birthday(1996,12,12) days_bir=Days(time.localtime().tm_year,birthday.mon,birthday.day) days_cur=Days(time.localtime().tm_year,time.localtime().tm_mon,time.localtime().tm_mday) t1=Teacher('Eav-J',22,'女',birthday,days_bir) print(t1.view_info()) print("距离您生日还有%s天"%(t1.cal_days_dif(days_cur)))
运行结果:
这里有一个问题,我是暴力解决的,比如说我生日是 4-12 但现在9-17号,今年生日已经过去了,怎么计算离下次生日还有多久~