Python:类的继承实例

class School(object):
def init(self,name,addr): #构造函数,用来初始化
self.name=name
self.addr=addr
self.staffs=[]
self.students=[]

def enroll(self,stu_obj): #注册学生
   print("为学员 %s 办理注册手续" %stu_obj.name)
   self.students.append(stu_obj)

def hire(self, staff_obj): #雇佣老师
    print("雇 %s 为老师" % staff_obj.name)
    self.staffs.append(staff_obj)

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):#新式类继承法,继承父类schoolMember
def init(self,name,age,sex,salary,course):
super(Teacher,self).init(name,age,sex) #新式类继承法
self.salary=salary
self.course=course
def tell(self):
print('''----info of Teacher:%s----
Name:%s
Age:%s
Sex:%s
Salary:%s
Course:%s
''' % (self.name,self.name,self.age,self.sex,self.salary,self.course))
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) # 新式类写法,是用来解决多重继承问题的,
#在super机制里可以保证公共父类仅被执行一次,至于执行的顺序,是按照mro进行的(E.mro)。
#注意super继承只能用于新式类,用于经典类时就会报错。
#新式类:必须有继承的类,如果没什么想继承的,那就继承object
#经典类:没有父类,如果此时调用super就会出现错误:『super() argument 1 must be type, not classobj』,
self.stu_id=stu_id
self.grade=grade

def tell(self): #介绍自己,重构父类方法
    print('''---info of Teacher:%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))

school=School('old boy1','沙河') #实例化一个学校
t1=Teacher("李明",33,'F',15000,"Linux") #实例化一个老师
t2=Teacher("李立",23,'M',12000,"python")

s1=student("王丽",19,'F',1001,'Linux')#实例化一个学生
s2=student("李丽明",23,'M',1002,'python')

school.enroll(s1) #学校注册一个学生
school.enroll(s2) #学校注册一个学生
school.hire(t1) #学校雇佣一个老师
school.hire(t2) #学校雇佣一个老师

t1.tell()
s1.tell()

print(school.students) #打印学生列表
print(school.staffs)

school.staffs[0].teach() #让老师讲课

for stu in school.students:
stu.pay_tution(5000) #交学费

猜你喜欢

转载自blog.51cto.com/3906249/2301336