python类的封装

# Python 类的封装
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)
类的封装

猜你喜欢

转载自www.cnblogs.com/hellangels333/p/9023047.html