面向对象思想的编程----案例“人开枪射击子弹”

1.思想方法

①设计一个类

类名,属性,行为

②创建类

构造函数

③实例化对象

对函数传参

④访问对象方法

2.下面就用一个案例来做说明

人开枪射击子弹

首先我们思考 可以设计三个类 人,枪,弹夹


类名:Person
属性:gun
行为:fire


类名:Gun
属性:bulletBox
行为:shoot

弹夹
类名:BulletBox
属性:bulletCount
行为:

那么我们首先来写弹夹这个类

class BulletBox(object):
    def __init__(self, count):
        self.bulletCount = count

枪可以写成

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))

由于考虑到装弹的行为,所以人可以写成

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(4)
gun = Gun(bulletBox)
per = Person(gun)


per.fire()
per.fire()
per.fire()
per.fire()
per.fire()

per.fillBullet(2)
per.fire()
per.fire()
per.fire()

运行程序后将得到如下结果

剩余子弹:3发
剩余子弹:2发
剩余子弹:1发
剩余子弹:0发
没有子弹了
剩余子弹:1发
剩余子弹:0发
没有子弹了

这是利用面向对象思想来解决的整个过程了,希望你可以理解哦~~

猜你喜欢

转载自blog.csdn.net/weixin_44166997/article/details/85331030