Py003-01-04组合

继承是类与类之间的关系

组合

先看这样一段代码 老师和学生

  • 有共用的属性 school
  • 有重复的属性 name,age,sex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Teacher:
school = '中科院'

def __init__(self,name,age,sex,level,salary):
self.name = name
self.age = age
self.sex = sex

self.level = level
self.salary = salary

def teach(self):
print('%s is teaching'%self.name)


class Student:
school = '中科院'
def __init__(self,name,age,sex,classname):
self.name = name
self.age = age
self.sex = sex

self.classname = classname

def learn(self):
print('%s is learning'%self.name)

提取公共

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class People:
school = '中科院'
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex


class Teacher(People):
def __init__(self,name,age,sex,level,salary):
super().__init__(name,age,sex)
self.level = level
self.salary = salary

def teach(self):
print('%s is teaching'%self.name)


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

def learn(self):
print('%s is learning'%self.name)

老师有课程,如果都教 python呢?

1
2
3
4
5
6
7
8
9
10
11
12
class Teacher(People):
def __init__(self,name,age,sex,level,salary,course_name,course_price,course_period):
super().__init__(name,age,sex)
self.level = level
self.salary = salary
self.course_name = course_name
self.course_price = course_price
self.course_period = course_period

# 这样就又重复了 俩个老师都教 python
t1 = Teacher('阮老师',49,'man',10,3000,'python',30000,'半年')
t2 = Teacher('廖雪峰',59,'man',10,3000,'python',30000,'半年')

继续提取课程 类

1
2
3
4
5
6
7
8
9
class Course:
def __init__(self,course_name,course_price,course_period):
self.course_name = course_name
self.course_price = course_price
self.course_period = course_period

python = Course('python',30000,'半年')

此时老师和课程的关系?
  • 继承的关系是?——什么是什么
  • 组合呢?——什么有什么 如:老师有课程 学生有课程
1
2
3
4
5
6
7
8
9
10
11
t1 = Teacher('阮老师',49,'man',10,3000)
t2 = Teacher('廖雪峰',59,'man',10,3000)

t1.course = python
t2.course = python

# 访问t1/t2老师的课程名称
t1.course.course_name
t2.course.course_name

这种方式不是继承而是组合