主體
import random
import time
class Bot:
wait = 1
def __init__(self):
self.q = ""
self.a = ""
def _think(self,s):
return s
def _say(self,s):
time.sleep(Bot.wait)
print(s)
def run(self):
self._say(self.q)
self.a = input()
self._say(self._think(self.a))
#子類——問名字
class Hello(Bot):
def __init__(self):
self.q = "What's your name?"
def _think(self,s):
return f"Hello,{s}!"
#子類——問心情
class Feeling(Bot):
def __init__(self):
self.q = "How are you today?"
def _think(self,s):
if "good" in s.lower():
return "I'm feeling good too!"
else:
return "sorry to hear that."
#子類——問顏色
class Color(Bot):
def __init__(self):
self.q = "What's your favorite color?"
self.a = ""
def _think(self,s):
Color = ['red','yellow','oringe','blue','purple','black','white']
return f"You like {s}, that's a great color. My favorite color is {random.choice(Color)}!"
裝載、調(diào)用各類機(jī)器人的方法
class Garfield:#定義一個用來裝載、調(diào)用機(jī)器人的類,命名為加菲貓。
def __init__(self):#用初始化方法,定義初始參數(shù):各類機(jī)器人的數(shù)組。
self.bots = []
def add(self,bot):#將各類機(jī)器人加入機(jī)器人組合的方法。
self.bots.append(bot)
def run(self):#加菲貓的運(yùn)行方法。
print("welcome!")
for bot in self.bots:
bot.run()
garfield = Garfield()#類函數(shù)的實(shí)例化
garfield.add(Hello())#調(diào)用類中的add方法
garfield.add(Feeling())
garfield.add(Color())
garfield.run()#加載完成,調(diào)用run方法運(yùn)行。