python面向对象封装
# 面向对象封装案例:为新房子增添家具# 分析对象的属性# 房子属性:户型、面积 # 家具属性: 家具名称、占地面积 class Furniture: def __init__(self, name, area): self.name = name self.area = area def __str__(self): return F"[{self.name}]占地面积{self.area}平方米" class House: def __init__(self, house_type, area): self.house_type = house_type self.area = area self.free_area = area self.furnitures = [] def __str__(self): return F"房子户型:{self.house_type}\n占地面积:{self.area}平方米\n家具包含:{self.furnitures}\n剩余面积:{self.free_area}" def add(self, furniture): if self.free_area < furniture.area: return self.furnitures.append(furniture.name) self.free_area -= furniture.area # 创建房子对象 my_house = House("一室一厅", 60) # 创建家具对象 bed = Furniture("席梦思", 11) chair = Furniture("实木椅", 0.5) # 为房子添加家具 my_house.add(bed) my_house.add(chair) print(my_house)
输出:
房子户型:一室一厅 占地面积:60平方米 家具包含:[‘席梦思‘, ‘实木椅‘] 剩余面积:48.5
相关推荐
随心而作 2020-06-13
zhaoyizhu0 2014-11-16
鹤之淇水 2019-03-18
HMHYY 2019-03-17
zhangsteak 2016-08-30
爱狗者 2016-02-19
zhangdeTalk 2019-01-01
李叫兽 2018-05-14
雅趣 2018-03-15
小饭桌 2018-02-12
北欧半月谈 2018-01-30
北欧半月谈 2018-01-30
住范儿 2017-12-27
软件设计 2017-05-18
互联网小兵 2017-04-07