• python中的面向对象学习之继承实例讲解


    __author__ = "Yanfeixu"
    
    class School(object):  # 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):
            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)
            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_tuition(self,amount):
            print("%s has paid tution for $%s"% (self.name,amount) )
    
    
    school = School("老男孩IT","沙河")
    
    t1 = Teacher("Oldboy",56,"MF",200000,"Linux")
    t2 = Teacher("Alex",22,"M",3000,"PythonDevOps")
    
    s1 = Student("ChenRonghua",36,"MF",1001,"PythonDevOps")
    s2 = Student("徐良伟",19,"M",1002,"Linux")
    
    
    t1.tell()
    s1.tell()
    school.hire(t1)
    school.enroll(s1)
    school.enroll(s2)
    
    print(school.students)
    print(school.staffs)
    school.staffs[0].teach()
    
    for stu in school.students:
        stu.pay_tuition(5000)
    

    实现的功能如下图所示(可以帮助深入理解类的继承):
    在这里插入图片描述

    本人目前在学习python、前端、数据库和linux相关的内容,故打算写一些学习笔记,包括安装软件遇到的一些问题、编程语言的学习。 学习如逆水行舟,你在原地踏步的同时,别人一直在前进!
  • 相关阅读:
    验证数字范围的小插件
    解决EJB懒加载问题
    JS获取按键的代码,Js如何屏蔽用户的按键,Js获取用户按键对应的ASII码(兼容所有浏览器)
    struts2标签之<s:select>
    c#(winform)中自定义ListItem类方便ComboBox和ListBox添加项完全解决
    辞职前须慎重考虑
    怎样把PDF文件在WinForm窗口中显示出来
    加载报表失败
    经典正则表达式 Javascript
    无法生成项目输出组“内容文件来自...
  • 原文地址:https://www.cnblogs.com/souhaite/p/10585603.html
Copyright © 2020-2023  润新知