python_Daily practice (每日一练) 93

关卡三:

1.练习题1
扩展应用
要求:
思考,抽象出一个类
提供基本属性、基本的方法
通过类创建出几个不同的对象
打印它们的属性、调用它们的方法
提示:
提取一类具体的对象的相同(或者类似)属性和行为然后成为一个类

2.练习题2
烤地瓜应用智能版
要求:
完善烤地瓜应用
先实现以下方法:
cook() : 把地瓜烤一段时间
addCondiments() : 给地瓜添加配料
init() : 设置默认的属性
str() : 让print的结果看起来更好一些
然后实现以下方法:
auto_addCondiments(): 自动随机添加一种配料
auto_cook(): 自动烤地瓜,当地瓜烤熟了,自动停止

注意属性名和方法名不能同名

#定义地瓜
import random
class SweetPotato:
‘这是烤地瓜的类’

#定义初始化方法
def __init__(self):
    self.cookedLevel = 0
    self.cookedString = "生的"
    self.condiments = []
#定制print时的显示内容
def __str__(self):
    msg = self.cookedString + " 地瓜"
    if len(self.condiments) > 0:
        msg = msg + "("
        for temp in self.condiments:
            msg = msg + temp + ", "
        msg = msg.strip(", ")
        msg = msg + ")"
    return msg

#烤地瓜方法
def cook(self, time):
    self.cookedLevel += time
    if self.cookedLevel > 8:
        self.cookedString = "烤成灰了"
    elif self.cookedLevel > 5:
        self.cookedString = "烤好了"    
    elif self.cookedLevel > 3:
        self.cookedString = "半生不熟"
    else:
        self.cookedString = "生的"

#添加配料
def addCondiments(self, condiments=["番茄酱","沙拉酱","芥末酱","辣椒酱"]):
    index = random.randint(0,len(condiments)-1)
    self.condiments.append(condiments[index])

def auto_cook(self, timestep=1):
    cmd = input("请问您需要几分熟(7-10):")
    while True:
        self.cook(timestep)
        # 添加佐料
        if self.cookedLevel>=4 and len(self.condiments)==0:
            self.addCondiments()
        if cmd == "7" and self.cookedLevel == 4:
            print("7分熟:",self)
            break
        elif cmd == "8" and self.cookedLevel == 5:
            print("8分熟:",self)
            break
        elif cmd == "9" and self.cookedLevel == 6:
            print("9分熟:",self)
            break
        elif cmd == "10" and self.cookedLevel == 7:
            print("10分熟:",self)
            break
        elif self.cookedLevel == 8:
            print("完全熟了:",self)
            break

digua = SweetPotato()
digua.auto_cook()

提示:
auto_cook方法使用循环,调用cook方法,每次循环都判断一次地瓜的状态,一旦地瓜烤熟了,就立刻使用break终止循环
auto_addCondiments方法: 可以先在__init__方法中,为地瓜设计一个condiments属性,类型为列表,数据如[“番茄酱”,“沙拉酱”,“芥末酱”,“辣椒酱”]等等,然后在调用cook方法时,随机选择一种,作为配料来添加

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值