代码上传至github
此代码已上传至github,喜欢的给个star噢。嘻嘻~~
python3.6版本
Person.py
import datetime
class Person:
AllCount = 0
def __init__(self,number,name,sex,birthday):
self.number = number
self.name = name
self.birthday = birthday
self.sex = sex
Person.AllCount += 1
@property
def age(self):
return datetime.date.today().year - self.birthday.year
@age.setter
def age(self,value):
return AttributeError("禁止赋值年龄")
@age.deleter
def age(self):
return AttributeError("年龄不能删除")
def __repr__(self):
return "<个人:{} at 0x{}>".format(self.number,id(self))
def __str__(self):
return "编号:{},姓名:{},性别:{}".format(self.number,self.name,self.sex)
def __del__(self):
Person.AllCount -= 1
Department.py
class Department:
def __init__(self,depnumber,adminstrate,louceng):
self.depnumber = depnumber
self.adminstrate = adminstrate
self.louceng = louceng
def __str__(self):
return "编号:{},管理者:{},楼层:{}".format(self.depnumber,self.adminstrate,self.louceng)
Teacher.py
from OO.Person import Person as Person
from OO.Department import Department as Department
class Teacher(Person):
TeacherCount = 0
def __init__(self, number,name,sex,birthday,depatment:Department, salay):
super().__init__(number,name,sex,birthday)
self.depatment = depatment
self.salay = salay
Teacher.TeacherCount += 1
def give_raise(self, percent, bonus=.0):
self.salay = self.salay * (1 + percent) + bonus
def __del__(self):
Teacher.TeacherCount -= 1
def __str__(self):
return "编号:{},姓名:{},性别:{},部门:{}".format(self.number, self.name, self.sex,self.depatment)
Student.py
from OO.Person import Person as p
class Student(p):
StudentCount = 0
def __init__(self,number,name,sex,birthday,grade):
super().__init__(number,name,sex,birthday)
#Person.__init__(self,number,name,sex,birthday) 或者可以这样写
self.grade = grade
Student.StudentCount += 1
def __del__(self):
Student.StudentCount -= 1
def __str__(self):
return "编号:{},姓名:{},性别:{}".format(self.number,self.name,self.sex)
main.py
import datetime
#注意包的导入格式
from OO.Person import Person as Person
from OO.Teacher import Teacher as Teacher
from OO.Student import Student as Student
from OO.Department import Department as Department
if __name__ == '__main__':
per = Person ("1","wu","女",datetime.date(1995,5,10))
dep = Department("x","wi",6)
tea = Teacher("1","wu","女",datetime.date(1995,5,10),dep,5000)
stu = Student("a","li","男",datetime.date(1998,2,15),90)
stu2 = Student("b", "Zhou", "女", datetime.date(1998, 2, 19), 80) #必须是stu2,stu 是占原来的位置,使得stu.StudentCount不会加1
#感受下两者区别,因为age使用了装饰器property且 @age.deleter进行修饰,所以age不能删除。同时为age的修改的函数也进行了修饰
# del (per.age)
# del (per.sex)
# print(per.age)
# print(per.sex)
#
#
# print(per) #调用Person.py里的__str()__函数
# #脚本中直接写 per 调用__repr__(self)函数
# print(tea.depatment.depnumber) #获取教师所在的部门编号
print(per.AllCount)
print(tea.TeacherCount)
print(stu.StudentCount)
其中
super() 函数是用于调用父类(超类)的一个方法。
super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。