[root@localhost 05-class]# cat cook_sweet_potato.py
‘‘‘
思考:
1.定义一个地瓜类
2.有什么方法,什么属性
‘‘‘
#1.定义一个地瓜类
class cook_sweet_potato():
def __init__(self):
self.cooked_string = "生的"
self.cooked_level = 0
self.condiments = [] #为了能够存储多个数据,往往在开发中让一个属性是列表
def __str__(self):
return "地瓜 状态:%s(%d),添加的佐料有:%s"%(self.cooked_string,self.cooked_level,str(self.condiments))
def cook(self,cooked_time):
self.cooked_level += cooked_time
if self.cooked_level >= 0 and self.cooked_level<3:
self.cooked_string = "生的"
elif self.cooked_level >=3 and self.cooked_level<5:
self.cooked_string = "半生不熟"
elif self.cooked_level >=5 and self.cooked_level<=8:
self.cooked_string = "熟了"
elif self.cooked_level >8:
self.cooked_string = "烤糊了"
def add_condiments(self,item):
#因为item这个变量指向了一个佐料,所有接下来需要将item放到append里面
self.condiments.append(item)
#2.创建了一个地瓜对象
sweetPotato = cook_sweet_potato()
#print(sweetPotato)
#3.开始烤地瓜
cooked_time = int(input("请输入你要烤地瓜的时间:"))
sweetPotato.cook(cooked_time)
sweetPotato.add_condiments("孜然")
sweetPotato.add_condiments("辣椒")
sweetPotato.add_condiments("芥末")
print(sweetPotato)
原文地址:http://blog.51cto.com/huwho/2113321