如果输入 Len > 20,则生成不同消息的子类方法

Subclass Method That Generates Different Message If Input Len > 20

我正在尝试创建一个可以与人进行简单对话的聊天机器人。聊天机器人需要一个子类 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 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)

什么是prompt_from_human?你如何从 bored(self) 得到它? return(response) 也会抛出一些错误,因为 1) self.response() 是实际函数,但 2) response 也未定义。


所以,为了解决这些问题,我真的认为您根本不需要 bored 函数。您应该改写 response 函数和 return 超级函数,以保持对象函数的一致性。

class BoredChatbot(Chatbot):

    def response(self, prompt_from_human):
    """ 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 super(BoredChatbot, self).response(prompt_from_human)

然后sally = BoredChatBot("Sally"),当然