python烤地瓜实例(深入理解面向对象编程)

#定义一个地瓜类
class SweetPotato:
    def __init__(self):
        self.cookedString = "生的"
        self.cookedLevel = 0
        self.condiments = []#为了能够存储多个数据,往往在开发中让一个属性是列表

    def __str__(self):
        return "地瓜 状态:%s(%d),添加的作料有:%s"%(self.cookedString, self.cookedLevel, str(self.condiments))

    def cook(self, cooked_time):

        #因为这个方法被调用了多次,为了能够在一次调用这个方法的时候能够获取到上一次调用这个方法时cooked_time
        #所以需要在此把cooked_time保存到对象的属性中,因为属性不会随着方法的调用而结束
        #说白了就是比如先放盐再放酱油,放酱油的时候盐是放了的
        #一个方法被调用的时候可以用局部变量来保存数据,但是当这个方法定义结束之后这个方法中的所有数据就没有了
        self.cookedLevel += cooked_time

        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 = "烤糊了"
            
	#因为item这个变量指向了一个 作料,所以 接下来需要将item放到append里面
    def addCondiments(self, item):
        self.condiments.append(item)


#创建了一个地瓜对象
di_gua = SweetPotato()
print(di_gua)


#开始烤地瓜
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.addCondiments("白糖")
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
di_gua.addCondiments("番茄酱")
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
di_gua.addCondiments("辣椒")
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.addCondiments("孜然")
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)
di_gua.cook(1)
print(di_gua)

发布了4 篇原创文章 · 获赞 2 · 访问量 48

猜你喜欢

转载自blog.csdn.net/qq_42776165/article/details/104746187