学习内容:
1,类
2,构造函数
3,析构函数
4,私有属性
5,继承
6,多继承
类 class
一个类即是对一类拥有相同属性的对象的抽象、蓝图、原型。在类中定义了这些对象的都具备的属性(variables(data))、共同的方法
class school(object): #创建类 def __init__(self,name,addr): #类的初始化,self是必须存在,其他参数可自定义 self.name = name #参数定义 self.addr = addr
已经定义好一个类,那我们又如何执行呢?
school = school("szu","nanshanqu") #定义变量名,第一个school相当于定义初始化的self,szu赋给name,addr是nanshanqu
这些初始化的属性,也称为静态属性。
类的继承
一个类可以派生出子类,在这个父类里定义的属性、方法自动被子类继承
class school(object): def __init__(self,name,addr): self.name = name self.addr = addr self.students = [] self.staffs = [] def enroll(self,stu_obj): #类中定义的功能,学校具有为学生注册的功能,和雇佣老师的功能。这都是school这个类的动态属性,所以从新定义了一个函数 print("成功为\033[31;1m%s\033[0m注册" %stu_obj.name) self.students.append(stu_obj) def hire(self,staff_obj): print("成功雇佣\033[31;1m%s\033[0m" %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): passclass student(schoolmember): #类的继承,继承了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 pay_tution(self,amount): print("%s学生成功缴费%s" %(self.name,amount)) 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))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,course): print("%s老师正在上%s课程" %(self.name,self.course))s1 = student("小张",22,"男",1001,"研1")s2 = student("小ma",22,"男",1002,"研2")t1 = teacher("德玛西亚",42,"男",100000, '语文')t2 = teacher("沃尔玛",32,"女",60000, '数学')s1.tell()t1.tell()s1.pay_tution(10000)t1.teach('语文')school = school("szu","nanshangqu")school.hire(t1)school.enroll(s1)
完整实现了面向对象编程,对于之后要是往学生或者老师这个类中加属性都非常方便
作业: