面向對象: ...
面向對象:
1. 烤麵包
class Bread: #定義初始化方法 def __init__(self): self.cookedlevel = 0 self.cookedstr = '生的' self.sauce = []#調味料 def __str__(self): msg = self.cookedstr + '麵包' if len(self.sauce) > 0: msg = msg + '(' for temp in self.sauce: msg = msg + temp + ', ' msg = msg.strip(', ')#去掉字元串尾部“, ” msg = msg + ')' return msg def cook(self, time): self.cookedlevel += time if self.cookedlevel > 10: self.cookedstr = '焦的' elif self.cookedlevel > 7: self.cookedstr = '熟的' elif self.cookedlevel > 4: self.cookedstr = '半熟' else: self.cookedstr = '生的' def addsauce(self, sauce): self.sauce.append(sauce) bread1 = Bread() print('一團麵粉:') print(bread1.cookedlevel) print(bread1.cookedstr) print(bread1.sauce) print('做麵包…………烤麵包') print('4 min 後:') bread1.cook(4) print(bread1) print('6 min 後:') bread1.addsauce('奶油') bread1.cook(6) print(bread1) print('11 min 後:') bread1.addsauce('芝麻') bread1.cook(11) print(bread1)
2. 存傢具
class Home: def __init__(self, area): self.area = area self.furniture = [] def __str__(self): msg = '當前房間可用面積為:' + str(self.area) if len(self.furniture) > 0: msg += '容納物品為:' for temp in self.furniture: msg += temp.getname() + ', ' msg = msg.strip(', ') return msg def contain(self, item): needarea = item.getarea() if self.area > needarea: self.furniture.append(item) self.area -= needarea print('存儲 OK') else: print('錯誤') class Bed: def __init__(self, area, name = '床'): self.area = area self.name = name def __str__(self): msg = '床的面積為:' + str(self.area) return msg def getname(self): return self.name def getarea(self): return self.area myhome = Home(100) print(myhome) print('-'*50) mybed = Bed(20) print(mybed) myhome.contain(mybed) print(myhome) print('-'*50) mybed2 = Bed(30, '絨棉床') print(mybed2) myhome.contain(mybed2) print(myhome)