python类的封装、继承、多态


#案例:小智今天想出去,但不清楚今天的天气是否适宜出行,需要一个帮他提供建议的程序,程序要求输入daytime

#和night,根据可见度和温度给出出行建议和使用的交通工具,需要考虑需求变更的可能
#需求分析:使用python类的封装、继承、多态比较容易实现,由父类封装查看可见度和查看温度的方法,
#子类继承父类。若有需要,子类可以覆盖父类的方法,做自己的实现。子类也可以自定义方法
#
#
class WeatherSearch(object):
def __init__(self,input_daytime):
self.input_daytime = input_daytime

def seach_visibility(self):
visible_leave = 0
if self.input_daytime == 'daytime':
visible_leave = 2
if self.input_daytime == 'night':
visible_leave = 9
return visible_leave

def seach_temperature(self):
temperature = 0
if self.input_daytime == 'daytime':
temperature = 26
if self.input_daytime == 'night':
temperature = 16
return temperature

class OutAdvice(WeatherSearch):
def __init__(self,input_daytime):
#继承父类的__init__方法
WeatherSearch.__init__(self,input_daytime)

#子类覆盖父类的方法 多态
def seach_temperature(self):
vehicle = ''
if self.input_daytime == 'daytime':
vehicle = 'bike'
if self.input_daytime == 'night':
vehicle = 'taxi'
return vehicle
def out_advice(self):
visible_leave = self.seach_visibility()
if visible_leave == 2:
print('The weatheris good,suitable for use %s.'%self.seach_temperature())
elif visible_leave == 9:
print('The weather os bad.you should use %s.'%self.seach_temperature())
else:
print('The weather is beyond my scope, I can not give you any adice')

check = OutAdvice('nigt')
check.out_advice()
摘自《python3.5从零开始学》-刘宇宙 编著

猜你喜欢

转载自www.cnblogs.com/aanb/p/9994946.html