烤地瓜
# 1,定义类:初始化属性,被烤和添加调料的方法,显示对象信息的str
class SweetPotato():
# 定义初始化对象
def __init__(self):
# 被烤的时间
self.cook_time = 0
# 地瓜的状态
self.cook_static = '生的'
# 添加调料
self.condiments = []
# 2,创建对象并调用对应的实例方法
def cook(self, time):
# 1,先计算地瓜整体烤过的时间
self.cook_time += time
# 2,用整体烤过的时间在判断地瓜的状态
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}'
digua = SweetPotato()
# print(digua)
digua.cook(2)
digua.add_condiments('白砂糖')
print(digua)
刚刚开始学习面向对象了,这个实例学习是真的不错,和大家分享一下。