Python2.7从函数中获取返回值而不再次运行函数中的内容?

2024-10-01 09:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

有人知道怎么做吗?在

我试图得到一个函数的返回值。。但我不希望函数再次运行。这是语音识别,所以,每次它再次运行时,它都会尝试查看用户所说的话。我只需要保存变量。在

顺便说一下,我也不能使用全局变量。在

编辑:

def voiceRecognition(self):
    <A bunch of voice recognition stuff here>
    return whatUserSaid

我称之为代码:

^{pr2}$

SPEECH和self的原因是b/c,它是类的一部分,我在另一个Python文件中调用它。现在它正在工作。。。我只需要返回变量whatUserSaid,而不需要重新运行函数来获取值。在


Tags: of函数用户self编辑def语音voice
2条回答

您可以使用一个类实例并记下该值。在

class VoiceRecognizer():

     def __init__(self):
         self._parsed = {}

     def recognize(self, speech):
         key = function_to_turn_speech_into_unique_string(speech)
         if key not in self._parsed:
             self._parsed[key] = recognize_function(speech)
         return self._parsed[key]

 recognizer = VoiceRecognizer()
 recognizer.recognize(speechA)  # will compute
 recognizer.recognize(speechA)  # will use cache
 recognizer.recognize(speechB)  # will compute if speechA == speechB

从你给定的代码来看,看起来你已经把它构建到一个类中了,所以我要做一些假设。在

class VoiceRecognizer(object):
    def __init__(self, *args, **kwargs):
        self.last_phrase = None

    def voiceRecognition(self):
        # your code here
        self.last_phrase = whatUserSaid
        return whatUserSaid

这可以让你做如下事情:

^{pr2}$

但我不知道你为什么要这么做。你不能把它保存到变量里吗?在

last_phrase = v.voiceRecognition() # like this?

相关问题 更多 >