面向对象-组合
组合为什么有什么
继承实现代码重用
class People: school="luffcity" def __init__(self, name, age, sex,): self.name = name self.age = age self.sex = sex class Teacher(People): schoole='Luffycity' def __init__(self,name,age,sex,level,salary): super(Teacher,self).__init__(name,age,sex) self.level=level self.salary=salary def teach(self): print("%s is teaching" % self.name) class Student(People): schoole = 'Luffycity' def __init__(self, name, age, sex, class_time): super(Student, self).__init__(name, age, sex) self.class_time=class_time def learn(self): print("%s is learning" % self.name) t1=Teacher('alex',18,'male',10,3000) s1=Student('zhangsan',28,'female','08:30:00')
给老师添加其他属性,如课程信息,按如上方法,每次创建老师对象,都会传入相同参数,解决办法如下
class People: school="luffcity" def __init__(self, name, age, sex,): self.name = name self.age = age self.sex = sex class Teacher(People): schoole='Luffycity' def __init__(self,name,age,sex,level,salary): super(Teacher,self).__init__(name,age,sex) self.level=level self.salary=salary def teach(self): print("%s is teaching" % self.name) class Student(People): schoole = 'Luffycity' def __init__(self, name, age, sex, class_time): #super()关键字继承 super(Student, self).__init__(name, age, sex) self.class_time=class_time def learn(self): print("%s is learning" % self.name) #定义一个课程类 class Course: def __init__(self,course_name,course_price,course_period): self.course_name=course_name self.course_price=course_price self.course_period=course_period #创建一个python课程对象 python=Course('python',3000,'3mons') t1=Teacher('alex',18,'male',10,3000) t2=Teacher('aglo',88,'male',90,1000) #给t1添加课程对象 t1.course=python #给t2添加课程对象 t2.course=python #访问t1的课程对象 print(t1.course.course_name) print(t1.course.course_price) print(t1.course.course_period) #访问t2的课程对象 print(t2.course.course_name) print(t2.course.course_price) print(t2.course.course_period)
在Course类中也可以添加其他方法,如添加一个查看课程信息的方法
class Course: def __init__(self,course_name,course_price,course_period): self.course_name=course_name self.course_price=course_price self.course_period=course_period def course_info(self): print("课程名<%s>课程价格<%s>课程周期<%s>" % (self.course_name,self.course_price,self.course_period))
访问course_info()方法
t1=Teacher('alex',18,'male',10,3000) t1.course=python t1.course.course_info()
即老师有课程
学生加一个日期属性
class Date: def __init__(self,year,mon,day): self.year=year self.mon=mon self.day=day def tell_info(self): print("%s-%s-%s" % (self.year,self.mon,self.day)) d=Date(2010,4,20) student1=Student('张三',28,'female','08:30:00') student1.birh=d student1.birh.tell_info()