Loading... <div class="panel panel-default collapse-panel box-shadow-wrap-lg"><div class="panel-heading panel-collapse" data-toggle="collapse" data-target="#collapse-9a99cd29583500f694251874e3001fb972" aria-expanded="true"><div class="accordion-toggle"><span style="">题目</span> <i class="pull-right fontello icon-fw fontello-angle-right"></i> </div> </div> <div class="panel-body collapse-panel-body"> <div id="collapse-9a99cd29583500f694251874e3001fb972" class="collapse in collapse-content"><p></p> ``` 1)主程序只负责创建房子对象和家具对象。 2)让房子对象调用add_item方法将家具添加到房子中。 3)面具计算、剩余面积、家具列表等处理都被封装在房子类的内部。 ``` <p></p></div></div></div> ## 代码 ``` class Home: def __init__(self, home_name, area): self.home_name = home_name self.area = area self.freearea = area self.jiaju = [] def __str__(self): return "户型:{} \n总面积:{}\n剩余面积:{}\n家具名:{}".format(self.home_name, self.area, self.freearea, self.jiaju) def add_item(self, itm): print("添加", itm) # 判断家具的面积 if itm.area > self.freearea: print("{}的面积太大,无法添加!".format(itm.name)) return # 将家具的名称添加到列表 self.jiaju.append(itm.name) # 计算剩余面积 self.freearea -= itm.area class jiaju(): def __init__(self, name, area): self.name = name self.area = area def __str__(self): return "[{}]:占地 [{}] 平米".format(self.name, self.area) # 创建家具 bed = jiaju("床", 4) chest = jiaju('衣柜', 2) table = jiaju('餐桌', 1.5) # 创建房子 myhome = Home('三室一厅', 100) myhome.add_item(bed) myhome.add_item(bed) myhome.add_item(bed) myhome.add_item(chest) myhome.add_item(table) print(myhome) ``` 最后修改:2021 年 10 月 14 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 1 如果觉得我的文章对你有用,请随意赞赏
3 条评论
牛啊牛啊
嘿嘿
(☆ω☆)