裝載、調(diào)用各類機(jī)器人的方法

主體

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)行。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容