python(27)- 面向对象练习Ⅰ
一:定义如下类,并最大程度地重用代码(继承,派生:子类重用父类方法,组合)
老师类
学生类
分数类
课程类
生日类
class People: def __init__(self,name,age,birth): self.name = name self.age = age self.birth=birth class Teacher(People): #继承People def __init__(self,name,age,birth,course): People.__init__(self,name,age,birth) #子类重用父类方法 self.course=course #派生 class Student(People): #继承People def __init__(self,name,age,birth,course,score): People.__init__(self,name,age,birth) #子类重用父类方法 self.course=course #派生 self.score=score #派生 class Course: def __init__(self,name,price,period): self.name=name self.price=price self.period=period class Score: def __init__(self,level): self.level=level class Birth: def __init__(self,year,mouth,day): self.year=year self.mouth=mouth self.day=day #类Teacher“调用”了类Birth的方法,达到了组合的效果 #同样类Student“调用”了类Birth、类Course、类Score的方法,使用了组合的概念 t1=Teacher("egon",68,Birth(1949,10,1),Course("python",15800,"6m")) s1=Student("xuyaping",18,Birth(1949,10,1),Course("python",15800,"6m"),Score("A")) print(s1.birth.year,s1.birth.mouth,s1.birth.day) print(t1.course.name,t1.course.price,t1.course.period) print(s1.score.level)
二:实现如图的继承关系,然后验证经典类与新式类在查找一个属性时的搜索顺序
#python3中新式类 class B: def test(self): print("from B") pass class C: def test(self): print("from C") pass class D(B,C): def test(self): print("from D") pass class E(B,C): def test(self): print("from E") pass class F(D,E): def test(self): print("from F") pass f=F() f.test() print(F.__mro__) --->(<class '__main__.F'>, <class '__main__.D'>, <class '__main__.E'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>)
#python2中 #coding:utf8 class B: def test(self): print("from B") pass class C: def test(self): print("from C") pass class D(B,C): def test(self): print("from D") pass class E(B,C): def test(self): print("from E") pass class F(D,E): def test(self): print("from F") pass f=F() f.test() #F--->D--->B--->C--->E
三:基于多态的概念来实现linux中一切皆文件的概念:文本文件,进程,磁盘都是文件,然后验证多态性
多态性:一种调用方式,不同的执行效果(多态性) class All_file: def write(self): pass def read(self): pass class Txt(All_file): def write(self): print("文本数据的写入") def read(self): print("文本数据的读取") class Process(All_file): def write(self): print("进程数据的写入") def read(self): print("进程数据的读取") class Sata(All_file): def write(self): print("磁盘数据的写入") def read(self): print("磁盘数据的读取") t=Txt() p=Process() s=Sata() def func(obj): obj.write() obj.read() func(t) --->文本数据的写入 文本数据的读取 func(p) --->进程数据的写入 进程数据的读取 func(s) --->磁盘数据的写入 磁盘数据的读取