class Gun: def __init__(self, model): # 1. 枪的型号 self.model = model # 2. 子弹的数量 self.bullet_count = 0 def add_bullet(self, count): self.bullet_count += count def shoot(self): # 1. 判断字弹的数量 if self.bullet_count <= 0: print("[%s] 没有字弹了..." % self.model) return # 2. 发射子弹 self.bullet_count -= 1 # 3. 提示发射信息 print("[%s] 突突突...子弹有: [%d]" % (self.model, self.bullet_count)) # 创建枪对象 ak47 = Gun('ak47') ak47.add_bullet(30) ak47.shoot() ak47.shoot() class Soldier: def __init__(self, name): self.name = name self.gun = None # 私有 def fire(self): # 1. 判断士兵是否有枪 if self.gun is None: # 身份运算符(is) 可以替换(==) print("[%s] 还没有枪..." % self.name) return # 2. 口号 print("冲啊... [%s]" % self.name) # 3. 装子弹 self.gun.add_bullet(30) # 4. 发射子弹 self.gun.shoot() # 创建一个士兵 jack = Soldier("jack") jack.gun = ak47 jack.fire() #print(jack.gun)
输出:
C:\Users\79453\Anaconda3\python.exe "D:/PyCharm 2018.1/pycorrector-master/tests/self_model.py" [ak47] 突突突...子弹有: [29] [ak47] 突突突...子弹有: [28] 冲啊... [jack] [ak47] 突突突...子弹有: [57] Process finished with exit code 0