1. 程式人生 > 其它 >組合與反射以及面向物件的內建函式

組合與反射以及面向物件的內建函式

組合

  1、概念

    組合就是一個物件擁有一個屬性,該屬性的值是另外一個物件

  2、作用

    解決類與類之間的程式碼冗餘問題

  3、程式碼

class People():
    school = 'SH'

    def __init__(self, name, age, gender, ):
        self.name = name
        self.age = age
        self.gender = gender


class Admin(People):
    pass


class Course():
    def __init__
(self, name, period, price, ): self.name = name self.period = period self.price = price python = Course('python', '6mon', 10000) linux = Course('linux', '5mon', 20000) class Student(People, Course): def __init__(self, name, age, gender, course=None): if course is None: course
= [] self.courses = course super().__init__(name, age, gender, ) def choose_course(self, stu_obj, course): stu_obj.courses.append(course) class Teacher(People, Course): def __init__(self, name, age, gender, level): self.level = level super().__init__
(name, age, gender, ) def score(self, stu_obj, score): stu_obj.score = score tea = Teacher('tony', 19, 'male', 10) tea.course = linux print(tea.course.name) print(tea.course.price) print(tea.course.period)