转载自:https://blog.csdn.net/damys/article/details/78497689
1 class Gun: 2 def __init__(self, model,color): 3 4 # 1. 枪的型号 5 self.model = model 6 self.color = color 7 8 # 2. 子弹的数量 9 self.bullet_count = 0 10 11 def add_bullet(self, count): 12 13 self.bullet_count += count 14 15 def shoot(self): 16 17 # 1. 判断字弹的数量 18 if self.bullet_count <= 0: 19 print("[%s] 没有字弹了..." % self.model) 20 return 21 22 # 2. 发射子弹 23 self.bullet_count -= 1 24 25 # 3. 提示发射信息 26 print("[%s] 突突突...子弹有: [%d]" % (self.model, self.bullet_count)) 27 28 class Soldier: 29 def __init__(self, name): 30 self.name = name 31 self.gun = None # 私有 32 33 def fire(self): 34 # 1. 判断士兵是否有枪 35 if self.gun is None: # 身份运算符(is) 可以替换(==) 36 print("[%s] 还没有枪..." % self.name) 37 return 38 39 # 2. 口号 40 print("冲啊... [%s]" % self.name) 41 42 # 3. 装子弹 43 self.gun.add_bullet(30) 44 45 # 4. 发射子弹 46 self.gun.shoot() 47 print(self.gun.color) 48 ak47 = Gun('ak47','red') 49 ak47.add_bullet(30) 50 ak47.shoot() 51 ak47.shoot() 52 jack = Soldier('jack') 53 jack.gun = ak47 54 jack.fire() 55 print(jack.gun)
我在这里面自己加了一个颜色属性color,就是为了说明这个Soldier类里面的属性gun可以是Gun这个类,然后Gun这个类也是有自己的属性的比如color,当然也有自己的方法,如加子弹(add_bullet)这个其实就和我这5.18到5.20这个周末一直纠结的那个SCI2的问题的解释差不多,那个的代码是:
1 class G(): 2 def __init__(self,node): 3 self.node = node 4 print("A G class is created!") 5 class node(): 6 def __init__(self,clolor,value,size): 7 self.value = value 8 self.clolor = clolor 9 self.size = size 10 11 node1 = node('red',[1],10) 12 node2 = node('yellow',[4],20) 13 nodesall = [] 14 nodesall.append(node1) 15 nodesall.append(node2) 16 g1 = G(nodesall) 17 m = g1.node[:] 18 print(type(g1.node)) 19 print(type(g1)) 20 for item in m: 21 print(item) 22 print(m[0].clolor) 23 print(m[1].clolor)
这里也是我自己定义的G类里面有属性node,然后node也有自己的属性如color、size这些。