class SweetPotato():
def init(self):
# 烤的時間
self.cook_time = 0
# 地瓜的狀態
self.cook_state = '生的'
# 調料列表
self.condiments = []
def cook(self, time):
"""烤地瓜的方法"""
# 烤的時間,狀態
self.cook_time += time
if 0 <= self.cook_time < 3:
self.cook_state = '生的'
elif 3 <= self.cook_time < 5:
self.cook_state = '半生不熟'
elif 5 <= self.cook_time < 8:
self.cook_state = '熟了'
else:
self.cook_state = '燒焦了'
def add_condiments(self, condiment):
"""用戶意願的調料追加到調料列表"""
self.condiments.append(condiment)
def __str__(self):
return f"這個地瓜總共烤了{self.cook_time}分鐘,狀態是{self.cook_state},調料有{self.condiments}"
i = 0
while i < 8:
sweetPotato = SweetPotato()
time = int(input('預烤時間為:'))
sweetPotato.cook(time)
condiment = input('調料為:')
sweetPotato.add_condiments(condiment)
print(sweetPotato)
i += time
因為實例化放在while裡面了,這樣每次執行都會創建一個新的實例
試試看把sweetPotato = SweetPotato()放在while前面
i = 0
sweetPotato = SweetPotato()
while i < 8:
time = int(input('預烤時間為:'))
sweetPotato.cook(time)
condiment = input('調料為:')
sweetPotato.add_condiments(condiment)
print(sweetPotato)
i += time