Python学习之类的组合
#!/usr/bin/env python #-*-coding:utf8-*- class School(object): def __init__(self,name,addr): self.name = name self.addr = addr self.students = [] self.staffs = [] def enroll(self,stu_obj): print("为学员%s办理注册手续"%stu_obj.name) self.students.append(stu_obj) def hire(self,staff_obj): self.staffs.append(staff_obj) print("雇佣新员工%s"%staff_obj.name) class SchoolMember(object): def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def tell(self): pass class Teacher(SchoolMember): # 重构父类构造函数 def __init__(self,name,age,sex,salary,course,School): # 实例化Teacher(子类)的时候传name,age,sex三个参数给父类 #先把父类的构造函数覆盖了 #再继承 #再添加自己的东西 #调用父类的初始化,将父类中的属性进行初始化,并且将self对象作为参数传递到父类的初始化函数中 super(Teacher,self).__init__(name,age,sex) # 实例化Teacher(子类)的时候传name,age,sex三个参数给父类 self.school = School #类的组合,相当于school = School("尚硅谷","沙河"),实例化一个school,实例化teacher的时候把school传到了里面,调用时使用self.school.name self.salary=salary self.course=course def tell(self): print(''' ----info of Teacher:%s---- Name:%s Age:%s Sex:%s Salary:%s Course:%s School:%s '''%(self.name,self.name,self.age,self.sex,self.salary,self.course,self.school.name)) def teach(self): print("%s is teaching course [%s]"%(self.name,self.course)) class Student(SchoolMember): def __init__(self,name,age,sex,stu_id,grade): super(Student,self).__init__(name,age,sex) self.stu_id=stu_id self.grade=grade def tell(self): print(''' ----info of Student:%s---- Name:%s Age:%s Sex:%s Stu_id:%s grade:%s '''%(self.name,self.name,self.age,self.sex,self.stu_id,self.grade)) def pay_tution(self,amount): print("%s has paid tution for %s"%(self.name,amount)) #生成学校,老师,学生 school1 = School("尚硅谷","沙河") t1 = Teacher("Oldboy",56,"M",222222,"Linux",school1) #将School作为参数传递给教师实例 t2 = Teacher("alex",58,"W",100,"python",school1) s1 = Student("bbb",36,"MF",102,"python") s2 = Student("aea",86,"M",101,"linux") t1.tell() s1.tell() school1.hire(t1) school1.enroll(s1) school1.enroll(s2) print(school1.students) print(school1.staffs) school1.staffs[0].teach() for stu in school1.students: stu.pay_tution(5000)