首页 > 编程语言 > 详细

初识python: 继承实例 - 学校、老师、学生

时间:2019-08-26 16:45:03      阅读:151      评论:0      收藏:0      [点我收藏+]

对学校、老师、学生做一个分类,并抽象成类。并实现各自的一些功能。代码如下:

父类1:学校

技术分享图片
# 学校
class School(object):
    def __init__(self,name,addr):
        self.name = name
        self.addr = addr
        self.students = []
        self.teachers = []

    # 注册
    def stu_regin(self,stu_obj):
        print(给学员%s办理注册。%stu_obj.name)
        self.students.append(stu_obj)

    # 入职
    def tec_regin(self,tec_obj):
        print(给老师%s办理入职。%tec_obj.name)
        self.teachers.append(tec_obj)
学校

父类2:学校成员

技术分享图片
class SchoolMember(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def tell(self):
        print(学校成员信息。)
学校成员

子类1:老师

技术分享图片
# 老师
class Teacher(SchoolMember):
    def __init__(self,name,age,course,salary):
        super(Teacher,self).__init__(name,age)
        self.course = course
        self.salary = salary

    def tell(self):
        print(‘‘‘
        ---- %s老师的信息 ----
        姓名:%s
        年龄:%s
        课程:%s
        工资:%s
        ‘‘‘%(self.name,self.name,self.age,self.course,self.salary))

    def teach(self):
        print(%s老师正在给学生上%s课%(self.name,self.course))
老师

子类2:学生

技术分享图片
# 学员
class Student(SchoolMember):
    def __init__(self,name,age,stu_id,class_id,fee):
        super(Student,self).__init__(name,age)
        self.stu_id = stu_id
        self.class_id = class_id
        self.fee = fee

    def tell(self):
        print(‘‘‘
        ---- %s学生的信息 ----
        姓名:%s
        年龄:%s
        学籍号:%s
        班级:%s
        ‘‘‘ % (self.name, self.name, self.age, self.stu_id, self.class_id))

    def pay_fee(self):
        print(%s交了%s元学费。%(self.name,self.fee))
学生

实例化类:

技术分享图片
# 生成学校
sch = School(成都大学,成都)

# 生成老师
te1 = Teacher("张三",35,"python3",10000)
te2 = Teacher(李四,28,JAVA,10000)
te3 = Teacher(王五,25,C,10000)

# 生成学生
st1 = Student(李稍等,25,001,python入门班,8000)
st2 = Student(张撒旦,32,002,C入门班,5000)
st3 = Student(王而非,25,003,python入门班,8000)
实例化

查看老师信息,调用老师tell方法:

# 查看老师信息
te1.tell()

给老师办理入职,调用学校的tec_regin方法:

# 老师入职
sch.tec_regin(te1)

给学生办理注册,调用学校的stu_regin方法:

# 学生注册
sch.stu_regin(st1)
sch.stu_regin(st2)
sch.stu_regin(st3)

老师授课:

# 老师教课
sch.teachers[0].teach()

学生交学费:

# 学生交学费
for s in sch.students:
    s.pay_fee()

执行结果:

技术分享图片

 

初识python: 继承实例 - 学校、老师、学生

原文:https://www.cnblogs.com/simple-li/p/11413377.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!