装载、调用各类机器人的方法

主体

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)}!"

装载、调用各类机器人的方法

class Garfield:#定义一个用来装载、调用机器人的类,命名为加菲猫。
  def __init__(self):#用初始化方法,定义初始参数:各类机器人的数组。
    self.bots = []
  def add(self,bot):#将各类机器人加入机器人组合的方法。
    self.bots.append(bot)
  def run(self):#加菲猫的运行方法。
    print("welcome!")
    for bot in self.bots:
      bot.run()

garfield = Garfield()#类函数的实例化
garfield.add(Hello())#调用类中的add方法
garfield.add(Feeling())
garfield.add(Color())
garfield.run()#加载完成,调用run方法运行。

你可能感兴趣的:(装载、调用各类机器人的方法)