Combination concept |
In addition to inheritance, there is another important way of software reuse - composition .
Combination Definition
Composition refers to the use of objects (that is, instances) of another class as data attributes in one class, which is called class composition.
That is, a property of one class that is an object of another class is composition.
>>> class Equip: #Weapon equipment class ... def fire(self): ... print('release Fire skill') ... >>> class Riven: #The class of the hero Riven, a hero needs to have equipment, so it needs to combine the Equip class ... camp= ' Noxus ' ... def __init__ (self,nickname): ... self.nickname=nickname ... self.equip =Equip() #Use the Equip class to generate an equipment and assign it to the equip attribute of the instance ... >>> r1=Riven( ' Riven ' ) >>> r1.equip.fire() #You can use the methods held by the objects generated by the combined classes to release Fire skill
Inheritance vs Composition |
commonality
Both composition and inheritance are important ways to efficiently use existing class resources (code reuse).
difference
Inheritance: Establishing the relationship between the derived class and the base class is a "yes" relationship.
Composition: The relationship between a class and a composed class is established, which is a "there" relationship.
Applicable
Inheritance: When there are many common functions between classes, it is better to use inheritance to extract these common functions and make them into base classes.
Composition: When the classes are significantly different, and the smaller class is a required component of the larger class, composition is better.
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 ' , ' Shahe Domineering Gold Medal Teacher ' ) s1 =Student( ' bull grenade ' ,18, ' female ' ) python=Course('python','3mons',3000.0) linux=Course('python','3mons',3000.0) #Add courses for teacher egon and student s1 egon.course.append(python) egon.course.append(linux) s1.course.append(python) #Add student s1 for teacher egon egon.students.append(s1) #使用 for obj in egon.course: obj.tell_info()