python面向对象类的综合题_Python中面向对象(二)封装及练习

1.封装

#1.将属性和方法封装到一个抽象的类中

#2.外界使用类创建对象,对象调用方法

#3.对象方法的细节都被封装在类的内部

-------->题目要求:

需求:

1.李雷体重75.0公斤

2.李雷每次跑步会减肥0.5公斤

3.李雷每次吃东西体重会增加1公斤

-------->代码如下:

class Person():

def __init__(self,name,weight):

self.name = name

self.weight = weight

def __str__(self):

return '我的名字叫 %s 体重是 %.2f' %(self.name,self.weight)

def run(self):

print('%s爱跑步' %self.name)

self.weight -= 0.5

def eat(self):

print('%s吃东西' %self.name)

self.weight += 1

Lilei = Person('李雷',75.0)

Lilei.run()

print(Lilei)

Lilei.eat()

print(Lilei)

-------->测试结果:

2.练习

练习(一)

-------->(1)题目要求:

需求:

1.房子有户型,总面积和家具名称列表

新房子没有任何的家具

2.家具有名字和占地面积,其中

床:占4平米

衣柜:占2平米

餐桌:占1.5平米

3.将以上三件家具添加到房子中

4.打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表

-------->代码如下:

class Furniture():

def __init__(self,name,area):

self.name = name

self.area = area

def __str__(self):

return '[%s]占地: %.2f' %(self.name,self.area)

# bed = Furniture('bed',4)

# print(bed)

class House():

def __init__(self,house_type,area):

self.house_type = house_type

self.area = area

#剩余面积

self.free_area = area

self.item_list = []

def __str__(self):

return ('户型: %s\n总面积: %.2f[剩余面积: %.2f]\n家具:%s'

%(self.house_type,self.area,self.free_area,self.item_list))

def add_item(self,item):

#1.判断家具的面积

if item.area > self.free_area:

print('%s 的面积太大,无法添加' %item.name)

#2.添加家具

self.item_list.append(item.name)

#3.计算剩余面积

self.free_area -= item.area

bed = Furniture('bed',4)

print(bed)

yigui = Furniture('yigui',200)

print(yigui)

table = Furniture('table',1.5)

print(table)

my_house = House('独门独栋',400)

my_house.add_item(bed)

my_house.add_item(yigui)

my_house.add_item(table)

print(my_house)

-------->测试结果:

练习(二)

-------->(2)题目要求:

1.士兵瑞恩有一把AK47

2.士兵可以开火(士兵开火扣动的是扳机)

3.枪 能够 发射子弹(把子弹发射出去)

4.枪 能够 装填子弹 --增加子弹的数量

简单方法:

Soldier Gun

name model

gun bullet_count #子弹数量足够多才能完

成射击的动作

init(self): init(self):

fire(self): add_bullet(self,count):#装填子弹的

方法

shoot(self):

-------->代码如下:

class Gun():

def __init__(self,model):

self.model = model

self.bullet_count = 0

def add_bullet(self,count):

self.bullet_count += count

def shoot(self):

if self.bullet_count <= 0:

print('%s没有子弹了...' %self.model)

self.bullet_count -= 1

print('%s ... %s' %(self.model,self.bullet_count))

class Soldier():

def __init__(self,name):

self.name = name

self.gun = None

def fire(self):

if self.gun == None:

print('%s还没有枪...' %self.name)

self.gun.add_bullet(5)

self.gun.shoot()

ak47 = Gun('ak47')

ak47.add_bullet(20)

ak47.shoot()

ryan = Soldier('Ryan')

ryan.gun = ak47

ryan.fire()

-------->测试结果:

标签:__,封装,name,area,Python,self,面向对象,item,def

来源: https://blog.csdn.net/qq_39376481/article/details/89219488

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值