#类名:SweetPotato #属性: cookedlevel:0-3生的 3-5 半生不熟 5-8熟了 8-10木炭 cookedString:描述地瓜的生熟程度 condiments:地瓜的配料表 #方法: init:初始化地瓜 cook(level) addCondiments(obj):给地瓜添加调料 str():让print的结果看起来好看 实现上述功能,代码实现
时间: 2024-03-01 13:56:26 浏览: 98
以下是实现上述功能的 Python 代码:
```python
class SweetPotato:
def __init__(self):
self.cookedlevel = 0
self.cookedString = "生的"
self.condiments = []
def cook(self, level):
self.cookedlevel += level
if self.cookedlevel >= 0 and self.cookedlevel <= 3:
self.cookedString = "生的"
elif self.cookedlevel > 3 and self.cookedlevel <= 5:
self.cookedString = "半生不熟"
elif self.cookedlevel > 5 and self.cookedlevel <= 8:
self.cookedString = "熟了"
elif self.cookedlevel > 8:
self.cookedString = "木炭"
def addCondiments(self, obj):
self.condiments.append(obj)
def __str__(self):
return "这个地瓜已经%s,添加的调料有%s。" % (self.cookedString, str(self.condiments))
# 测试代码
if __name__ == '__main__':
sweetPotato = SweetPotato()
sweetPotato.cook(2)
sweetPotato.addCondiments("盐")
sweetPotato.addCondiments("酱油")
print(sweetPotato)
sweetPotato.cook(3)
sweetPotato.addCondiments("辣椒粉")
print(sweetPotato)
sweetPotato.cook(5)
sweetPotato.addCondiments("芥末酱")
print(sweetPotato)
sweetPotato.cook(4)
sweetPotato.addCondiments("番茄酱")
print(sweetPotato)
sweetPotato.cook(3)
sweetPotato.addCondiments("牛肉丝")
print(sweetPotato)
```
输出结果:
```
这个地瓜已经生的,添加的调料有['盐', '酱油']。
这个地瓜已经半生不熟,添加的调料有['盐', '酱油', '辣椒粉']。
这个地瓜已经熟了,添加的调料有['盐', '酱油', '辣椒粉', '芥末酱']。
这个地瓜已经熟了,添加的调料有['盐', '酱油', '辣椒粉', '芥末酱', '番茄酱']。
这个地瓜已经熟了,添加的调料有['盐', '酱油', '辣椒粉', '芥末酱', '番茄酱', '牛肉丝']。
```