程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python object-oriented OOP programming (4)--combination relationship between objects

編輯:Python

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()


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved