1 ''' 2 给一套房子装修即房子里面添加家具 3 1. 家具的属性 4 1. 名称 5 2. 大小/面积 6 2. 房子的属性 7 1. 位置 8 2. 总面积 9 3. 空闲面积 10 3. 房子的行为: 11 1. 置办家具 12 ''' 13 14 15 class Furniture(): # 类定义有名称后面还有1个() 16 ''' 17 家具类 18 ''' 19 20 def __init__(self, name, area): 21 self.name = name 22 self.area = area 23 24 def __str__(self): 25 return self.name 26 27 28 class Home(): 29 ''' 30 房子类 31 ''' 32 33 # 构造器 34 def __init__(self, address, area): 35 # 房子的位置 36 self.address = address 37 # 房子的总面积 38 self.area = area 39 # 房子剩余面积(其他面积布置了家具) 40 self.free_area = area 41 # 新建房子,是空空的 42 self.furnitures = [] 43 44 def __str__(self): 45 furniture_names = [furniture.name for furniture in self.furnitures] 46 # return f'房子地理位置在{self.address},房子面积是{self.area},房子剩余面积是{self.free_area},房子有家具{self.furnitures}' 47 return f'房子地理位置在{self.address},房子面积是{self.area},房子剩余面积是{self.free_area},房子有家具{furniture_names}' 48 49 # 置办家具 50 def add_furniture(self, item): 51 if item.area <= self.free_area: 52 self.furnitures.append(item) 53 self.free_area = self.area - item.area 54 else: 55 print(f"家具{item}太大,剩余面积不足,无法容纳") 56 57 58 if __name__ == '__main__': 59 # 创建床、沙发对象 60 bed = Furniture("双人床", 6) 61 sofa = Furniture("沙发", 10) 62 63 home = Home("南京", 666) 64 print(home) # 房子地理位置在南京,房子面积是666,房子剩余面积是666,房子有家具[] 65 # 置办家具床 66 home.add_furniture(bed) 67 # 置办家具沙发 68 home.add_furniture(sofa) 69 # print(home) # 房子地理位置在南京,房子面积是666,房子剩余面积是656,房子有家具[<__main__.Furniture object at 0x0000018BE1B86750>, <__main__.Furniture object at 0x0000018BE1B868D0>] 70 print(home) # 房子地理位置在南京,房子面积是666,房子剩余面积是656,房子有家具['双人床', '沙发'] 71 72 basketball_court = Furniture("室内篮球场", 1000) 73 home.add_furniture(basketball_court)
标签:__,area,self,房子,案例,置办,家具,furniture From: https://www.cnblogs.com/allenxx/p/17566852.html