combination
1. In addition to the inheritance relationship between classes and classes, there is also a combination relationship in python.
What is composition - is resolving one class as a property of another class.
It is to solve the problem of what a class [has]. eg: Students [have] courses, teachers [have] courses.
The difference between inheritance and composition:
1. Inheritance - "The problem solved: what is [is] what is the relationship: eg students [are] human beings, teachers [are] human beings.
Usage: When there are many identical functions in a class, use the class to extract these functions to form a base class.
2. The problem solved by the combination—": What is the relationship between [there] and what: eg, students [have] courses, teachers [have] courses
Usage: When a class [has] certain functions. eg: Teachers have birthdays, teachers have students.
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()
Summarize:
Composition is better when the classes are significantly different and the smaller class is a component of the larger class.