练习题1
小花体重67公斤,小明体重95公斤
小花每次跳绳会减肥2.5公斤,小明每次跑步可以减3公斤
他们二个每次吃东西增加1公斤
参考答案:
class Person:
def __init__(self,name,weight,type): #对象的属性
self.name=name
self.weight=weight
self.type=type
def sport(self,nums): #将减肥的归到一类中
self.weight-=nums
print(f"{self.name}每次{self.type}会减{nums}公斤,做完后体重为:{self.weight}公斤")
def eat(self):
self.weight+=1
print(f"{self.name}每次吃东西会增加1公斤,吃完后体重为:{self.weight}公斤")
c1=Person("小花",67,"跳绳")
c1.sport(2.5)
c1.eat()
c2=Person("小明",95,"跑步")
c2.sport(3)
c2.eat()
练习题2
演示手机 要求: 手机电量默认是100 打游戏每次消耗电量10 听歌每次消耗电量5 打电话每次消耗电量4 接电话每次消耗电量3 充电可以为手机补充电量
参考答案:
class Phone:
def __init__(self):
self.battery=100
def play_game(self,type1,nums:int):
if self.battery>nums:
self.battery-=nums
print(f"{type1}结束,手机电量还剩{self.battery}")
elif self.battery==nums:
print("手机5秒后关机")
else:
print("手机电量不足,")
def chongdian(self,nums:int):
if self.battery>=100:
print("手机已满")
else:
self.battery+=nums
print(f"手机电量已增加{nums},当前电量为{self.battery}")
c1=Phone()
c1.play_game("打游戏",10)
c1.play_game("听歌",5)
c1.play_game("打电话",4)
c1.play_game("接电话",3)
c1.play_game("看电影",2)
c1.chongdian(10)
练习题3
反恐精英基础版 演示反恐精英 对一个匪徒 警察是子弹伤害为10 恐怖分子子弹伤害是5 枪枪命中 反恐精英: 警察 和 恐怖分子 血量都是100 模拟开枪 直到一人死亡
import random
class Person:
life=100
def __init__(self,name):
self.name=name
def __str__(self):
return f'self.name+"还剩"+str(self.life)+"血"'
class Police(Person):
def attack(self,terrorist):#警察攻击恐怖分子
terrorist.life-=10
print(f'{self.name}攻击了{terrorist.name},{terrorist.name}还剩{terrorist.life}血')
super().__str__()
class Terrorist(Person):
def shoot(self,police):#恐怖分子攻击警察
police.life-=5
print(f'{self.name}攻击了{police.name},{police.name}还剩{police.life}血')
super().__str__()
if __name__ == '__main__':
p=Police('警察')
print( p)
t=Terrorist('恐怖分子')
print( t)
while True:
n = random.choice([1, 2]) # 1警察发起攻击,2匪徒发起攻击
if n==1: #警察先
p.attack( t)
else:
t.shoot(p)
if t.life
文章来源于互联网:面向对象练习题
相关推荐: Windows 也能用 Claude Code?配合 Kimi K2,AI 编程体验直接起飞!
各位 AI 爱好者、编程小伙伴们,今天我要给大家带来一个超级炸裂的好消息:Claude Code 终于支持 Windows 了!没错,就是那个被誉为“AI 编程界的 GPT-4 终极对手”的 Claude Code,现在不仅能在 macOS、Linux 上撒欢…
5bei.cn大模型教程网










