【发布时间】:2016-12-16 23:42:12
【问题描述】:
我正在尝试创建一个可以与人类进行简单对话的聊天机器人。聊天机器人需要一个子类BoredChatbot,它将聊天机器人作为超类继承,但如果用户输入的长度超过 20 个字符,则会生成以下消息:
“zzz... Oh excuse me, I dozed off reading your essay.”
到目前为止我有:
class Chatbot:
""" An object that can engage in rudimentary conversation with a human. """
def __init__(self, name):
self.name = name
def greeting(self):
""" Returns the Chatbot's way of introducing itself. """
return "Hello, my name is " + self.name
def response(self, prompt_from_human):
""" Returns the Chatbot's response to something the human said. """
return "It is very interesting that you say: '" + prompt_from_human + "'"
# define a class called BoredChatbot
class BoredChatbot(Chatbot):
def bored(self):
""" Returns the Chatbot's response to length > 20 characters"""
if len(prompt_from_human) > 20:
return "zzz... Oh excuse me, I dozed off reading your essay."
else:
return(response)
sally = Chatbot("Sally")
human_message = input(sally.greeting())
print(sally.response(human_message))
这不起作用 - 它打印:
"It is very interesting that you say: + human_message"
不管长度。
我还尝试切换 if 语句的顺序,使其出现在方法之外。
class BoredChatbot(Chatbot):
def bored(self):
""" Returns the Chatbot's response to length > 20 characters"""
return "zzz... Oh excuse me, I dozed off reading your essay."
sally = BoredChatbot("Sally")
human_message = input(sally.greeting())
if len(human_message) > 20:
print(sally.bored(human_message))
else:
print(sally.response(human_message))
但这给了我一个错误信息:
AttributeError: 'Chatbot' object has no attribute 'bored' on line 31
为什么在BoredChatbot 中的方法注册不无聊?感谢您帮助我解决这个问题 - 我觉得它真的很接近。
【问题讨论】:
-
class Chatbot没有bored功能... -
另外,你从来没有创建过
BoredChatbot -
哦,我想当我在创建继承的 BoredChatbot(Chatbot) 类时添加了我在该类中放置的任何方法?
-
你的意思是把
sally = BoredChatBot("Sally")? -
如果
BoredChatbot实现了def response(因此覆盖了函数)本身,并且你在那里检查了长度,那么我认为这就是你想要的。添加bored()函数似乎不正确
标签: python class input subclass string-length