1. # 定义类:初始化属性,被烤和添加调料的方法,显示对象信息的str
    2. class SweetPotato():
    3. def __init__(self):
    4. #被烤的时间
    5. self.cook_time = 0
    6. # 烤的状态
    7. self.cook_state = "生的"
    8. # 调料列表
    9. self.condiments = []
    10. def cook(self,time):
    11. """烤地瓜方法"""
    12. # 1.先计算烤地瓜整体考过的时间
    13. self.cook_time += time
    14. # 2.用整体烤过的时间再判断地瓜的状态
    15. if 0 <= self.cook_time < 3:
    16. # 生的
    17. self.cook_state = "生的"
    18. elif 3 <= self.cook_time < 5:
    19. # 半生不熟
    20. self.cook_state = "半生不熟"
    21. elif 5 <= self.cook_time < 8:
    22. # 熟了
    23. self.cook_state = "熟了"
    24. elif self.cook_time >= 8:
    25. self.cook_state = "烤糊了"
    26. def add_condiments(self,condiment):
    27. # 用户意愿的调料追加到调料列表
    28. self.condiments.append(condiment)
    29. def __str__(self):
    30. return f"这个地瓜被烤的时间是{self.cook_time},状态是{self.cook_state},调料有{self.condiments}"
    31. # 创建对象并调用对应的实例方法
    32. digua1 = SweetPotato()
    33. print(digua1)
    34. digua1.cook(2)
    35. digua1.add_condiments("辣椒面")
    36. print(digua1)
    37. digua1.cook(2)
    38. print(digua1)

    运行结果如下:
    image.png

    说明:在调用时,是累加的,中间用了两次2分钟,也就是四分钟