首页 > 代码库 > 面向对象练习

面向对象练习

一:定义如下类,并最大程度地重用代码(继承,派生:子类重用父类方法,组合)
老师类
学生类
分数类
课程类
生日类

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)                                    

  

面向对象练习