python基础:面向对象的应用--烤地瓜。

烤地瓜

  • 1.需求主线:
  • 2.定义地瓜类
  • 3.创建对象,调用相关实例方法
  • 4.运行结果

1.需求主线:

被烤的时间和对应的地瓜状态:
0-3分钟:生的
3-5分钟:半生不熟
5-8分钟:熟的
超过8分钟:烤糊了
添加的调料:
用户可以按自己的意愿添加调料。

2.定义地瓜类

#定义地瓜类
class SweetPotato():
    #地瓜属性:
    def __init__(self):
        #烤的时间
        self.time=0
        #地瓜的状态
        self.static='生的'
        # 调料
        self.cdments=[]

    #定义烤地⽠瓜⽅方法
    def cook(self,time):
        self.time+=time
        if 0<=self.time<3:
            self.static='生的'
        elif 3<=self.time<5:
            self.static='半生不熟'
        elif 5<=self.time<8:
            self.static='熟了'
        elif self.time>=8:
            self.static='糊了'

    #定义添加佐料的方法
    def add_cdment(self,cdment):
        self.cdments.append(cdment)

    #显示地瓜的状态
    def printf(self):
        print(f'当前该地瓜烤的时间为:{self.time},状态为:{self.static},已经添加的佐料为:{self.cdments}。')

3.创建对象,调用相关实例方法

#创建一个 地瓜
sweetpotato1=SweetPotato()

#烤了2分钟,加上辣椒面,显示状态
sweetpotato1.cook(2)
sweetpotato1.add_cdment('辣椒面')
sweetpotato1.printf()
#再考2分钟,加 孜然 ,显示状态
sweetpotato1.cook(2)
sweetpotato1.add_cdment('孜然')
sweetpotato1.printf()
#再烤3分钟,显示状态
sweetpotato1.cook(3)
sweetpotato1.printf()
#再烤5分钟,显示状态
sweetpotato1.cook(5)
sweetpotato1.printf()

4.运行结果

在这里插入图片描述

你可能感兴趣的:(python,python,编程语言)