面向對象之組合

面向對象之組合

一、什麼是組合

組合是指一個對象中,包含另外一個或多個對象php

二、爲何要用組合

減小代碼冗餘python

三、耦合度

耦合度越高,程序的可擴展性越差app

耦合度越低,程序的可擴展性越高學習

四、組合的的使用

繼承:繼承是類與類之間的關係,子類繼承父類的屬性與方法,子類與父類是從屬關係code

組合:組合是對象與對象之間的關係,一個對象擁有另外一個或多個對象的屬性或方法對象

# 父類
class People:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex

# 學生類
class Student(People):
    def __init__(self,name, age, sex):
        super().__init__(name, age, sex)

    def learn(self):
        print('learning...')

# 老師類
class Teacher(People):
    def __init__(self,name, age, sex):
        super().__init__(name, age, sex)

    def teach(self):
        print('teach...')

# 時間類
class Date:
    def __init__(self,year,month,day):
        self.year = year
        self.month = month
        self.day = day
    def print_date(self):
        print(f'''
            生日爲{self.year}年{self.month}月{self.day}日
        ''')

stu_obj = Student('shen',18,'male')
date_obj = Date('2001','8','8')
# 將學生對象中加入日期對象
stu_obj.date_obj = date_obj
# 經過學生對象調用日期對象
stu_obj.date_obj.print_date()

teac_obj = Teacher('王',25,'female')
date_obj = Date('1996','8','8')
# 將老師對象中加入日期對象
teac_obj.date_obj = date_obj
# 經過學生對象調用日期對象
teac_obj.date_obj.print_date()
'''
練習需求:
    選課系統:
        1.有學生、老師類,學生與老師有屬性 「名字、年齡、性別、課程」,
        2.有方法 老師與學生能夠添加課程, 打印學習/教授課程。

    # 組合實現
'''

class People:
    def __init__(self, name, age, sex):
        self.name = name
        self.age = age
        self.sex = sex
    #打印生日
    def print_date(self):
        print(f'''
            生日{self.date_obj.year}年{self.date_obj.month}月{self.date_obj.day}日
        ''')
    # 添加課程到課程列表中
    def add_course(self, course_obj):
        self.course_list.append(course_obj)
    # 打印全部課程信息
    def print_all_course(self):
        for course_obj in self.course_list:
            course_obj.print_course_info()

class Student(People):
    def __init__(self,name, age, sex):
        super().__init__(name, age, sex)
        self.course_list = []

class Teacher(People):
    def __init__(self, name, age, sex):
        super().__init__(name, age, sex)
        self.course_list = []

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

class Course:
    def __init__(self, name, price, period):
        self.name = name
        self.price = price
        self.period = period
    # 打印一條課程信息
    def print_course_info(self):
        print(f'''
                課程名:{self.name} 課程價格:{self.price} 課程週期:{self.period}
           ''')

stu_obj = Student('shen', '18', 'male')
date_obj = Date(2001, 8, 8)
# 經過學生對象打印出生日
stu_obj.date_obj = date_obj
stu_obj.print_date()

course_obj1 = Course('python', '2000', '2')
course_obj2 = Course('php', '1800', '2')

teac_obj = Teacher('wang', 24, 'female')
# 爲老師添加課程
teac_obj.add_course(course_obj2)
teac_obj.add_course(course_obj1)
# 打印全部課程信息
teac_obj.print_all_course()
相關文章
相關標籤/搜索