面向对象之Shooting
对象 | 类名 | 属性 | 行为 |
---|---|---|---|
人 | Person | gun | fire |
枪 | Gun | bulletBox | shoot |
弹夹 | BulletBox | bulletCount |
######创建BulletBox类
class BulletBox(object):
def __init__(self, count):
self.bulletCount = count
创建Gun类
class Gun(object):
def __init__(self, bulletBox):
self.bulletBox = bulletBox
def shoot(self):
if self.bulletBox.bulletCount == 0:
print('子弹打光了,请装弹')
else:
self.bulletBox.bulletCount -= 1
print('剩余子弹%d发' % (self.bulletBox.bulletCount))
创建Person类
class Person(object):
def __init__(self, gun):
self.gun = gun
def fire(self):
self.gun.shoot()
def fillBullet(self, count):
self.gun.bulletBox.bulletCount = count
引用类、创建对象
# 引用类
from person import Person
from gun import Gun
from bulletbox import BulletBox
# 对象
bulletBox = BulletBox(3)
gun = Gun(bulletBox)
per = Person(gun)
per.fire()
per.fire()
per.fire()
per.fire()
per.fillBullet(3)
per.fire()
per.fire()
per.fire()
per.fire()