Python——组合与继承 发表于 2018-11-05 | 分类于 Python入门 | | 阅读数 字数统计: 235 | 阅读时长 ≈ 1 什么是组合解决类与类之间代码冗余的问题有两种解决方案: 继承 :描述的是类与类之间的关系 组合:描述的是一个类产生的对象,该对象拥有一个属性,这个属性的值是来自于另一个类的对象 12345678910111213141516171819202122232425262728293031323334353637383940class Date: def __init__(self,year,mon,day): self.year = year self.mon = mon self.day = day def tell_brith(self): print('出生日期<%s-%s-%s>' %(self.year,self.mon,self.day))class People: school = 'Lixin' def __init__(self,name,age,gender): self.name = name self.age = age self.gender = genderclass Teacher(People): def __init__(self,name,age,gender,level,salary): super().__init__(name,age,gender) self.level = level self.salary = salary def change_score(self): print('%s teacher is changing score.' %self.name)class Student(People): def __init__(self,name,age,gender,course): super().__init__(name,age,gender) self.course = course def choose(self): print('%s student is choosing courses.' %self.name)teacher_1 = Teacher('Lu',30,'male',10,10000)date_obj = Date(1988,1,1)date_obj.tell_brith()teacher_1.birth = date_obj # 为teacher_1 增加birth属性 值等于date_objteacher_1.birth.tell_brith() # teacher_1的名称空间等价于date_obj