作业1:
士兵老Amy有一把枪(AK47),
士兵可以开火
枪能够发射子弹
枪能够添加子弹
枪类:
属性:型号,子弹数量
行为:发射子弹,添加子弹
士兵类:
属性:士兵名称,枪支
行为:开火行为(需考虑到:是否有枪支?以及添加子弹,发射子弹)
解答:
class Soldier:
"士兵类"
def __init__(self,name):
self.name = name
self.gun = None
def __str__(self):
"士兵老Amy有一把枪(AK47)"
return "士兵%s有一把枪(%s)"%(self.name,self.gun)
def fire(self):
"开火行为"
if self.gun is None:
print(f"士兵{self.name}没枪")
else:
self.gun.shoot()
class Gun:
"枪类"
def __init__(self,type):
self.type = type
self.bullet_count = 0 # 子弹数量
def __str__(self):
return "%s 弹量还有%d发" % (self.type, self.bullet_count)
def add_bullet(self,count):
"装填子弹"
print(f"装弹{count}发")
self.bullet_count += count
def shoot(self):
"射击"
if self.bullet_count > 0:
self.bullet_count -= 1
print(f"射击1次,剩余弹量{self.bullet_count}")
else:
print('子弹用完了')
Amy = Soldier('老Amy')
Amy.gun = Gun('AK47')
print(Amy)
Amy.fire()
Amy.gun.add_bullet(20)
Amy.fire()
运行结果
!runfile('D:/腾讯课堂python学习/作业/2021.1.14(12次作业).py', wdir='D:/腾讯课堂python学习/作业')
士兵老Amy有一把枪(AK47 弹量还有0发)
子弹用完了
装弹20发
射击1次,剩余弹量19
作业2:
车类1:
属性:颜色,轮子个数(默认4个),重量级,速度(默认为0)
行为:加速,减速,停车
车类2:
属性:在基于车类1的基础上,添加一些比如:牌子,型号,空调系统等
行为:覆盖车类1的加速与减速,打印输出车辆信息
解答:
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 10:43:46 2021
@author: Administrator
"""
# 车类1:
# 属性:颜色,轮子个数(默认4个),重量级,速度(默认为0)
# 行为:加速,减速,停车
# 车类2:
# 属性:在基于车类1的基础上,添加一些比如:牌子,型号,空调系统等
# 行为:覆盖车类1的加速与减速,打印输出车辆信息
class Car1(object):
def __init__(self,color,num_wheel,weight_rate,speed=0):
self.color = color
self.num_wheel = 4
self.weight_rate = weight_rate
self.speed = speed
def accelerate(self):
print('加速')
def slow_down(self):
print('减速')
def stop(self):
print('停车')
class Car2(Car1):
def __init__(self, color, num_wheel, weight_rate, speed,brand,model,acs):
"acs :air conditioning system"
super().__init__(color, num_wheel, weight_rate, speed)
self.brand = brand
self.model = model
self.acs = acs
def accelerate(self,speed_num1):
self.speed_num1 = speed_num1
print(f'{self.brand}加速{self.speed_num1}')
def slow_down(self,speed_num2):
self.speed_num2 = speed_num2
print(f'{self.brand}减速{self.speed_num2}')
def print_inf(self):
print(f'车颜色:{self.color}\n重量级:{self.weight_rate}\n速度:{self.speed}\n品牌:{self.brand}\n型号:{self.model}\n空调系统:{self.acs}')
car_2 = Car2('白色', 4, '紧凑型',50,'宝马','X6','自动')
print(car_2.print_inf())
print(car_2.accelerate(5))
print(car_2.slow_down(10))
运行结果:
!runfile('D:/腾讯课堂python学习/作业/untitled2.py', wdir='D:/腾讯课堂python学习/作业')
车颜色:白色
重量级:紧凑型
速度:50
品牌:宝马
型号:X6
空调系统:自动
None
宝马加速5
None
宝马减速10
None