1. 程式人生 > >python類的封裝、繼承、多型

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從零開始學》-劉宇宙 編著