Python中多个类的使用实例
程序员文章站
2022-06-16 20:20:06
...
class FurnitureFeature(object):
def __init__(self, furniture_name, furniture_area):
self.furniture_name = furniture_name
self.furniture_area = furniture_area
print('家具名:%s\n占地面积:%.1f平方米' % (self.furniture_name, self.furniture_area))
class House(object):
def __init__(self, house_type, house_area):
self.house_type = house_type
self.house_area = house_area
self.house_furniture = []
self.house_area_left = house_area
def __str__(self):
return '户型:%s,总面积:%s平方米\n家具列表:%s\n剩余面积:%.1f平方米' % (
self.house_type, self.house_area, str(self.house_furniture).replace('[', '').replace(']', ''), self.house_area_left)
def add_furniture(self, FurnitureFeature):
if self.house_area_left > FurnitureFeature.furniture_area:
self.house_furniture.append(FurnitureFeature.furniture_name)
self.house_area_left = self.house_area_left - FurnitureFeature.furniture_area
return True
else:
return False
ALL = House('新房', 3)
bed = FurnitureFeature('床', 1.5)
table = FurnitureFeature('课桌', 1)
chest = FurnitureFeature('餐桌', 2)
for n in bed, table, chest:
if ALL.add_furniture(n):
print('%s添加成功!' % n.furniture_name)
else:
print('%s添加失败!空间不足!' % n.furniture_name)
print(ALL)