如何有效地评估一系列方法并调用那些不是False的方法?

时间:2018-12-13 14:47:58

标签: python class methods conditional

下面的类获取一个字符串作为输入,并通过answer()方法生成另一个字符串。

class Question:

    a = ["hello", "hi"]
    b = ["how are you", "how do you do"]
    c = ["how is the weather", "is it cold today"]

    def __init__(self, question):
        self.question = question

    def get_greeting(self):
        if self.question in Question.a:
            return "Hi There!"

    def get_health(self):
        if self.question in Question.b:
            return "I am fine"

    def get_weather(self):
        if self.question in Question.c:
            return "It is warm"

    def answer(self):

        if self.get_greeting():
            return self.get_greeting()
        elif self.get_health():
            return self.get_health()
        elif self.get_weather():
            return self.get_weather()
        else:
            return "I don't understand"

question = Question("how is the weather") 
print(question.answer()) # getting the output

对我来说,上面的做法很糟糕,因为answer()中的代码很长,并且每个方法调用两次。

因此,我想出了一个“更好的” answer()方法,该方法只调用一次,但是如果有条件的话,仍然很多。

def answer(self):

    result = self.get_greeting()
    if result:
        return result

    result = self.get_health()
    if result:
        return result

    result = self.get_weather()
    if result:
        return result

    return "I don't understand"

我认为这里可能还缺少其他一些技巧。有人可以提出建议吗?

2 个答案:

答案 0 :(得分:3)

如果or的结果不是“ false-y”,则为左操作数,否则为右操作数。
它还仅在需要时才评估右侧操作数。

def answer(self):
    return self.get_greeting() \
        or self.get_health() \
        or self.get_weather() \
        or "I don't understand"

答案 1 :(得分:2)

您可以对所有方法进行元组化,然后调用它们直到一个返回值:

def answer(self):
    methods = (self.get_greeting, self.get_health, self.get_weather)
    for m in methods:
        res = m()
        if res:
            return res
    return "I don't understand"

修改

如果您确实想创建许多方法并让您的answer()函数在不明确告诉您的情况下尝试全部方法,则可以使用以下代码:

def answer(self):
        getters = (v for k, v in self.__class__.__dict__.items() if k.startswith("get_"))
        for method in getters:
            res = method(self)
            if res:
                return res
        return "I don't understand"

编辑2

如果您的系统只是获取一个字符串作为输入并从中生成预定义的输出,则可以相当简化:

knowledge = [
    (["hello", "hi"], "Hi There"),
    (["how are you", "how do you do"], "I am fine"),
    (["how is the weather", "is it cold today"], "It is warm")
]

def answer(question):
    for inputs, answer in knowledge:
        if question in inputs:
            return answer
    return "I don't understand"

print(answer("hello"))

使用这种方法,向聊天机器人添加新短语就像在知识数据结构中添加一行一样容易。