Python面向对象练习

时间: 2023-09-30 admin IT培训

Python面向对象练习

Python面向对象练习

1)需求:
1.士兵瑞恩有一把AK47
2.士兵可以开火(士兵开火扣动的是扳机)
3.枪能够发射子弹–把子弹发射出去
4.枪能够装填子弹–增加子弹的数量
2)分析:
由于士兵瑞恩有一把AK47,士兵可以开火。故应该创建两个类:一个是士兵类,一个是枪类
枪类(Gun):
(1)属性:型号(model),弹夹中子弹的数目(bullet_count)
(2)方法:射击子弹(shoot),添加子弹(add_bullet)
士兵类(soldier):
(1)属性:姓名(name),枪名(Gun)
(2)方法:开火(fire)
3)代码的实现:

class Gun:def __init__(self,model,bullet_count):self.model = modelself.bullet_count = bullet_countdef __str__(self):return "%s,它有%d颗子弹" %(self.model,self.bullet_count)def shoot(self):if self.bullet_count == 0:return Falseelse:self.bullet_count -= 1print("正在射击...已经射中目标!")return Truedef add_bullet(self,count):self.bullet_count += countprint("已经填充了%d颗子弹" % count)return True
class Soldier:def __init__(self,name):self.name = nameself.gun = Nonedef __str__(self):return "%s有一把%s" % (self.name,self.gun)def fire(self):if self.gun == None:return Falseelse:self.gun.add_bullet(10)self.gun.shoot()return TrueB = Gun("ak47",30) #将枪实例化
A = Soldier("恩德")
A.gun = B  #将实例化的枪给士兵
A.fire()
print(A)

4)运行结果: