面向对象案例-烤红薯
类名设计:SweetPotato
分析“烤红薯”的属性
烤的时长:roast_time
烤的状态:roast_state
烤的风味:condiments
分析“烤红薯”的方法
烤红薯: roast
添加调料:add_condiments
烤的时长对应红薯的状态:
定义红薯类:
# 自定义红薯类 class SweetPotato(object): def __init__(self): # 烤的时长 self.roast_time = 0 # 烤的状态 self.roast_state = "生的" # 调味品 self.condiments = [] # 烤红薯 def roast(self, time): # 计算总的时间 self.roast_time += time # 焦了 if self.roast_time > 8: self.roast_state = "焦了" elif self.roast_time > 5: self.roast_state = "熟了" elif self.roast_time > 3: self.roast_state = "半生不熟" else: self.roast_state = "生的" # 添加调料 def add_condiment(self, name): self.condiments.append(name) # 追踪属性变化 def __str__(self): name = ",".join(self.condiments) if self.condiments else "原味" return """烤成的"%s"[%s]的红薯""" % (self.roast_state, name)
定义异常类:
# 自定义异常类 class TimeError(Exception): def __init__(self, time): self.time = time def __str__(self): return "亲!您传入的time实参数值有误!{time=%d}" % self.time
最终的红薯类:
# 自定义红薯类 class SweetPotato(object): def __init__(self): # 烤的时长 self.roast_time = 0 # 烤的状态 self.roast_state = "生的" # 调味品 self.condiments = [] # 烤红薯 def roast(self, time): if time <= 0: raise TimeError(time) # 计算总的时间 self.roast_time += time # 焦了 if self.roast_time > 8: self.roast_state = "焦了" elif self.roast_time > 5: self.roast_state = "熟了" elif self.roast_time > 3: self.roast_state = "半生不熟" else: self.roast_state = "生的" # 添加调味品 def add_condiment(self, name): self.condiments.append(name) # 追踪属性变化 def __str__(self): name = ",".join(self.condiments) if self.condiments else "原味" return """烤成的"%s"[%s]的红薯""" % (self.roast_state, name) if __name__ == '__main__': sp = SweetPotato() sp.roast(4) sp.roast(3) sp.add_condiment("孜然") sp.add_condiment("芥末") print(sp)
例子:
# 自定义红薯类 class SweetPotato(object): def __init__(self): # 烤的时长:roast_time self.roast_time = 0 # 烤的状态:roast_state self.roast_state = "生的" # 烤的风味:condiments self.__condiments = [] # 烤红薯 def roast(self, time): # 烤的总时长 self.roast_time += time # 通过总时长判断红薯的状态 # [0,) if self.roast_time < 3: pass # [3,5) elif self.roast_time < 5: self.roast_state = "半生不熟" # [5,8) elif self.roast_time < 8: self.roast_state = "熟了" # [8,+) else: self.roast_state = "焦了" # 添加佐料 def add_condiments(self, name): self.__condiments.append(name) # 追踪属性值变化 def __str__(self): # # 定义一个局部变量 保存口味 # name = None # # 判断是否是原味 # if not self.condiments: # name = "原味" # else: # name = ",".join(self.condiments) # 改成三目运算符 name = "原味" if not self.__condiments else ",".join(self.__condiments) return "红薯状态:%s,口味: %s" % (self.roast_state, name) # 创建一个红薯对象 sp = SweetPotato() # 烤1分钟 sp.roast(1) # sp.add_condiments("孜然") # sp.add_condiments("香辣") # 再烤4分钟 sp.roast(4) sp.add_condiments("孜然") sp.roast(3) print(sp)