一、需求
需求主线:
1. 被烤的时间和对应的地⽠状态:
   0-3分钟:⽣的
   3-5分钟:半⽣不熟
   5-8分钟:熟的
   超过8分钟:烤糊了
2. 添加的调料:
   ⽤户可以按⾃⼰的意愿添加调料
二、分析步骤
需求涉及⼀个事物: 地⽠,故案例涉及⼀个类:地⽠类
地⽠的属性
    被烤的时间
    地⽠的状态
    添加的调料
地⽠的⽅法
    被烤
        ⽤户根据意愿设定每次烤地⽠的时间
        判断地⽠被烤的总时间是在哪个区间,修改地⽠状态
    添加调料
        ⽤户根据意愿设定添加的调料
        将⽤户添加的调料存储
显示对象信息
三、代码实现
1、定义类
地⽠属性
定义地⽠初始化属性,后期根据程序推进更新实例属性
class SweetPotato():
 def __init__(self):
 # 被烤的时间
 self.cook_time = 0
 # 地⽠的状态
 self.cook_static = '⽣的'
 # 调料列表
 self.condiments = []
 
2、定义烤地瓜的方法
class SweetPotato():
 ......
 def cook(self, time):
 """烤地⽠的⽅法"""
    self.cook_time += time
    if 0 <= self.cook_time < 3:
       self.cook_static = '⽣的'
    elif 3 <= self.cook_time < 5:
       self.cook_static = '半⽣不熟'
    elif 5 <= self.cook_time < 8:
       self.cook_static = '熟了'
    elif self.cook_time >= 8:
       self.cook_static = '烤糊了'
       
3、书写str魔法⽅法,⽤于输出对象状态
class SweetPotato():
 ......
 def __str__(self):
     return f'这个地⽠烤了{self.cook_time}分钟, 状态是{self.cook_static}'
4、创建对象,测试实例属性和实例⽅法
digua1 = SweetPotato()
print(digua1)
digua1.cook(2)
print(digua1)
5、定义添加调料⽅法,并调⽤该实例⽅法
class SweetPotato():
 ......
 def add_condiments(self, condiment):
     """添加调料"""
     self.condiments.append(condiment)
 def __str__(self):
     return f'这个地⽠烤了{self.cook_time}分钟, 状态是{self.cook_static}, 添加的调料有{self.condiments}'
digua1 = SweetPotato()
print(digua1)
digua1.cook(2)
digua1.add_condiments('酱油')
print(digua1)
digua1.cook(2)
digua1.add_condiments('辣椒⾯⼉')
print(digua1)
digua1.cook(2)
print(digua1)
digua1.cook(2)
print(digua1)
四、代码总览
# 定义类
class SweetPotato():
 def __init__(self):
     # 被烤的时间
     self.cook_time = 0
     # 地⽠的状态
     self.cook_static = '⽣的'
     # 调料列表
     self.condiments = []
 def cook(self, time):
     """烤地⽠的⽅法"""
     self.cook_time += time
     if 0 <= self.cook_time < 3:
         self.cook_static = '⽣的'
     elif 3 <= self.cook_time < 5:
         self.cook_static = '半⽣不熟'
     elif 5 <= self.cook_time < 8:
         self.cook_static = '熟了'
     elif self.cook_time >= 8:
         self.cook_static = '烤糊了'
 def add_condiments(self, condiment):
     """添加调料"""
     self.condiments.append(condiment)
 def __str__(self):
     return f'这个地⽠烤了{self.cook_time}分钟, 状态是{self.cook_static}, 添加的调料有{self.condiments}'
     
digua1 = SweetPotato()
print(digua1)
digua1.cook(2)
digua1.add_condiments('酱油')
print(digua1)
digua1.cook(2)
digua1.add_condiments('辣椒⾯⼉')
print(digua1)
digua1.cook(2)
print(digua1)
digua1.cook(2)
print(digua1)