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)