'''
类的复合练习
向房子中添加家具
'''
# 设计一个房子类
class House(object):
def __init__(self,address, area):
self.address = address
self.area = area
self.free_area = self.area * 0.3
# 定义一个用来保存家具的容器属性
self.furniture = []
# 实现一个添加家具的方法
def add_furniture(self,fur):
# 先判断剩余 面积是否够添加 到房中
if fur.area < self.free_area:
self.furniture.append(fur)
self.free_area -= fur.area
print(f'剩余空间还有 {self.free_area} 平米')
else:
print('空间不够,无法添加新家具')
# 实现显示方法
def __str__(self):
s = f'我的大House在{self.address},占地{self.area}平方米 \n'
if len(self.furniture) == 0:
s += '还未添加家具 \n'
return s
else:
s += '家具如下: \n'
for f in self.furniture:
s += (str(f) )
return s
# 测试
home = House('博学家园96号701室', 100)
print(home)
# 添加家具
home.add_furniture(Furniture('双人床',6))
home.add_furniture(Furniture('饭桌',4))
home.add_furniture(Furniture('大衣柜',10))
home.add_furniture(Furniture('书桌',10))