composition and reusability
Combination refers to the use of objects of another class as data attributes in one class, also known as the combination of classes
In addition to inheritance, there is another important way of software reuse, namely: composition
>>> class Equip: #武器装备类
... def fire(self):
... print('release Fire skill')
...
>>> class Riven: #英雄Riven的类,一个英雄需要有装备,因而需要组合Equip类
... camp='Noxus'
... def __init__(self,nickname):
... self.nickname=nickname
... self.equip=Equip() #用Equip类产生一个装备,赋值给实例的equip属性
...
>>> r1=Riven('锐雯雯')
>>> r1.equip.fire() #可以使用组合的类产生的对象所持有的方法
release Fire skill
Both composition and inheritance are important ways to effectively utilize the resources of existing classes, but the concepts and usage scenarios of the two are different.
1. The way of inheritance
The relationship between the derived class and the base class is established through inheritance. It is a 'yes' relationship, such as a white horse is a horse, and a person is an animal.
When there are many common functions between classes, it is better to use inheritance to extract these common functions and make base classes. For example, teachers are people and students are people.
2. The way of combination
The relationship between the class and the combined class is established in a combined way. It is a 'has' relationship. For example, the professor has a birthday, the professor teaches python and linux courses, and the professor has students s1, s2, s3...
Example: Inheritance and Composition
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):
People.__init__(self,name,age,sex)
self.job_title=job_title
self.course=[]
self.students=[]
class Student(People):
def __init__(self,name,age,sex):
People.__init__(self,name,age,sex)
self.course=[]
egon=Teacher('egon',18,'male','沙河霸道金牌讲师')
s1=Student('牛榴弹',18,'female')
python=Course('python','3mons',3000.0)
linux=Course('python','3mons',3000.0)
#为老师egon和学生s1添加课程
egon.course.append(python)
egon.course.append(linux)
s1.course.append(python)
#为老师egon添加学生s1
egon.students.append(s1)
#使用
for obj in egon.course:
obj.tell_info()
Summarize:
Composition is better when the classes are significantly different and the smaller class is a required component of the larger class