The compositional relationship between objects is to put it bluntly, an instance of one class is used as an attribute of another class.
The reason for this relationship is (assuming that an instance of class A is used as an attribute of class B (don't care whether it is a class attribute or a member attribute, it belongs to a class or an attribute of instance B anyway)): class BToo complicated, too messy if everything is written in class B.
For example, in the next example of the man-dog war, if the fog is not taken out as a separate class, then the class attributes of the human class will eventually have many more attributes belonging to different weapons, such as the name of the knife, the attack value; the stickThe name, the attack value of the stick, etc., will be very messy, and now these weapons are grouped into one weapon class, it looks much better
Moreover, if these weapons are more complicated, you can also open a single class, such as knives, sticks, etc.
But due to the simplicity of the following example, the knife and stick are directly written in the weapon category,,,,
Then pay attention:
①Class A is an entity as an attribute of class B, so you have to instantiate class A when you use it
②Secondly, variables can be defined in functions in Python, which can be used as attributes of simple classes (if the classes are not complicated, think of the gun and stick classes in this example)
The code is as follows:
#The same class, the interaction between different instancesclass Weapon:def knife(self,obj_people,obj_dog):obj_dog.health_point -= 30print(obj_people.name,"Hit the dog with a knife",obj_dog.name,"The dog lost 30 blood, now the dog's blood is:",obj_dog.health_point)def stick(self, obj_people, obj_dog):obj_dog.health_point -= 20print(obj_people.name,"Hit the dog with a stick",obj_dog.name,"The dog lost 30 blood, now the dog's blood is:",obj_dog.health_point)class Dog:def __init__(self, dname):self.name = dnameself.health_point = 100def Info(self):print(self.name,"At this time, the blood volume is:",self.health_point)class People:def __init__(self, pname, page):self.name = pnameself.age = pageself.health_point = 100self.weapon = Weapon()p1 = People('zch',23)d1 = Dog('Jingba')p1.weapon.knife(p1,d1)p1.weapon.stick(p1,d1)d1.Info()