1 # 面向對象分析烤地瓜 2 3 # 1.抽象類 4 # 1.1人類 5 # 1.2地瓜類 6 7 8 # 分析人類裏面的屬性和方法 9 # 屬性:名字,性別,烤齡 10 # 方法:烤地瓜的方法,添加佐料 11 12 # 地瓜類中的屬性和方法 13 # 屬性:烤地瓜的狀態,烤地瓜的時間,佐料列表 14 # 方法:無 15 16 17 class Person(object): 18 def __init__(self,name,sex,roast_age): 19 self.name=name 20 self.sex=sex 21 self.roast_age=roast_age 22 # 烤地瓜的方法 23 def roast(self,time,current_sweet_potato): 24 #修改烤地瓜的總時間 25 current_sweet_potato.roast_time+=time 26 # 根據烤地瓜的時間,來設置烤地瓜的狀態 27 if current_sweet_potato.roast_time > 10: 28 # 修改烤地瓜的狀態 29 current_sweet_potato.roast_status = "烤糊了" 30 elif current_sweet_potato.roast_time > 8: # 時間範圍[9-10] 31 # 修改烤地瓜的狀態 32 current_sweet_potato.roast_status = "烤好了" 33 elif current_sweet_potato.roast_time > 5: # 時間範圍[6-8] 34 # 修改烤地瓜的狀態 35 current_sweet_potato.roast_status = "半生不熟" 36 else: 37 # 修改烤地瓜的狀態 38 current_sweet_potato.roast_status = "生的" 39 def add_condiment(self,condiment,current_sweet_potato): 40 # 把佐料添加到佐料列表 41 current_sweet_potato.condiment_list.append(condiment) 42 43 # 查看地瓜狀態 44 # def show_sweet_potato(self, current_sweet_potato): 45 # print(current_sweet_potato) 46 def __str__(self): 47 return "姓名: %s 性別:%s 烤齡: %d " % (self.name, self.sex,self.roast_age) 48 49 50 class SweetPotato(object): 51 def __init__(self): 52 # 烤地瓜的狀態 53 self.roast_status = "生的" 54 # 烤地瓜的時間 55 self.roast_time = 0 56 # 佐料列表屬性--> 存儲添加的佐料的 57 self.condiment_list = list() 58 59 def __str__(self): 60 if self.condiment_list: 61 # 代碼執行到此說明,佐料列表裏面有佐料信息 62 # 烤好了地瓜[番茄醬,孜然] 63 # 把佐料列表轉成字符串 64 # msg = self.roast_status + "地瓜" + str(self.condiment_list) 65 # 使用字符串利用字符串拼接的操做,把列表轉成字符串 66 condiment_str = ",".join(self.condiment_list) 67 # print(condiment_str, type(condiment_str)) 68 msg = self.roast_status + "地瓜" + "[" + condiment_str + "]" 69 return msg 70 else: 71 # 沒有佐料 72 return self.roast_status + "地瓜" 73 74 print("============準備一個地瓜==========") 75 sweet_potato = SweetPotato() 76 print(sweet_potato) 77 print("============準備找一個烤地瓜的師傅==============") 78 person = Person("老王","男",20 ) 79 print(person) 80 print("============先烤三分鐘==========") 81 person.roast(3, sweet_potato) 82 print(sweet_potato) 83 print("============再烤三分鐘==========") 84 person.roast(3, sweet_potato) 85 print(sweet_potato) 86 print("============再烤三分鐘==========") 87 person.roast(3, sweet_potato) 88 print(sweet_potato) 89 print("============添加佐料==========") 90 person.add_condiment("番茄醬", sweet_potato) 91 person.add_condiment("孜然", sweet_potato) 92 print(sweet_potato)