Python——类的封装

 1 class Gun:
 2     def __init__(self, model):
 3 
 4         # 1. 枪的型号
 5         self.model = model
 6 
 7         # 2. 子弹的数量
 8         self.bullet_count = 0
 9 
10     def add_bullet(self, count):
11 
12         self.bullet_count += count
13 
14     def shoot(self):
15 
16         # 1. 判断字弹的数量
17         if self.bullet_count <= 0:
18             print("[%s] 没有字弹了..." % self.model)
19             return
20 
21         # 2. 发射子弹
22         self.bullet_count -= 1
23 
24         # 3. 提示发射信息
25         print("[%s] 突突突...子弹有: [%d]" % (self.model, self.bullet_count))
26 
27 
28 # 创建枪对象
29 ak47 = Gun('ak47')
30 ak47.add_bullet(30)
31 ak47.shoot()
32 ak47.shoot()
33 
34 
35 class Soldier:
36     def __init__(self, name):
37         self.name = name
38         self.gun = None    # 私有
39 
40     def fire(self):
41         # 1. 判断士兵是否有枪
42         if self.gun is None:   # 身份运算符(is) 可以替换(==)
43             print("[%s] 还没有枪..." % self.name)
44             return
45 
46         # 2. 口号
47         print("冲啊... [%s]" % self.name)
48 
49         # 3. 装子弹
50         self.gun.add_bullet(30)
51 
52         # 4. 发射子弹
53         self.gun.shoot()
54 
55 # 创建一个士兵
56 jack = Soldier("jack")
57 jack.gun = ak47
58 jack.fire()
59 #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

猜你喜欢

转载自www.cnblogs.com/baobaotql/p/10714258.html