轉載自: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這些。
