1. 程式人生 > >派生組合示例

派生組合示例

class People:
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
class Course:
    def __init__(self,name,period,price):
        self.name=name
        self.period=period
        self.price=price
    def tell_info(self):
        print("%s %s %s"%(self.name,self.period,self.price))
class Teacher(People): def __init__(self,name,age,sex,job_title): super(Teacher,self).__init__(name,age,sex) #使用父類的__init__:先找到Teacher的父類,再把Teacher 的self(物件)傳給父類進行初始化 self.job_title=job_title self.course=[] self.students=[] class Student(People): def __init__
(self,name,age,sex): super(Student,self).__init__(name=name,age=age,sex=sex) self.course=[] wesley=Teacher('wesley',18,'male','nb') print(wesley.name,wesley.age,wesley.sex,wesley.job_title) s1=Student('hh',15,'female') print(s1.name,s1.age,s1.sex) python=Course('python','3months',3000) linux
=Course('linux','3months',3000) wesley.course.append(python) #組合,wesley.course 是python這個物件 wesley.course.append(linux) s1.course.append(python) # print(wesley.course) wesley.students.append(s1) for obj in wesley.course: #obj 是python,linux 物件 obj.tell_info() #呼叫物件的方法
wesley 18 male nb
hh 15 female
python 3months 3000
linux 3months 3000