面向对象之综合应用
- 烤地瓜
class Sweet():
def __init__(self):
#时间
self.cook_time=0
#状态
self.cook_state='生的'
#调料列表
self.condiments=[]
def cook(self,time):
"""烤地瓜方法"""
# 1.计算整体烤过的时间
self.cook_time+=time
# 2.用整体烤过的时间判断地瓜的状态
if 0<=self.cook_time<3:
self.cook_state='生的'
elif 3<=self.cook_time<5:
self.cook_state='半生不熟'
elif 5<=self.cook_time<8:
self.cook_state='熟了'
elif self.cook_time>=8:
self.cook_state='烤糊了'
def add_condiment(self,condiment):
# 用户意愿的调料追加到调料列表
self.condiments.append(condiment)
def __str__(self):
return f'这个地瓜被烤过的时间是{self.cook_time},状态是{self.cook_state},添加的调料是{self.condiments}'
digua1=Sweet()
print(digua1) #这个地瓜被烤过的时间是0,状态是生的,添加的调料是[]
digua1.cook(2)
digua1.add_condiment('糖')
print(digua1) #这个地瓜被烤过的时间是2,状态是生的,添加的调料是['糖']
digua1.cook(2)
digua1.add_condiment('盐')
print(digua1) #这个地瓜被烤过的时间是4,状态是半生不熟,添加的调料是['糖', '盐']
2.装家具
# 家具类
class Furniture():
def __init__(self,name,area):
# 家具名称
self.name=name
# 家具占地面积
self.area=area
# 房屋类
class Home():
def __init__(self,address,area):
# 地理位置
self.address=address
# 房屋面积
self.area=area
# 剩余面积
self.free_area=area
# 家具列表
self.furniture=[]
def __str__(self):
return f'房子的地理位置在{self.address},房屋的面积为{self.area},房屋的剩余面积为{self.free_area},家具列表为{self.furniture}'
def add_furniture(self,item):
if item.area<=self.free_area:
self.furniture.append(item.name)
self.free_area -= item.area
else:
print('家具太大,无法容纳')
home=Home('北京',1000)
print(home) #房子的地理位置在北京,房屋的面积为1000,房屋的剩余面积为1000,家具列表为[]
bed=Furniture('床',10)
home.add_furniture(bed)
print(home) #房子的地理位置在北京,房屋的面积为1000,房屋的剩余面积为990,家具列表为['床']
ball=Furniture('篮球场',2000)
home.add_furniture(ball)
print(home)
# 家具太大,无法容纳
# 房子的地理位置在北京,房屋的面积为1000,房屋的剩余面积为990,家具列表为['床']