Python2.7在不再次运行函数中的内容的情况下从函数中获取返回值?
我正在尝试获取函数的返回值。。但我不希望该函数再次运行。这是语音识别,因此,每次它再次运行时,它都会尝试查看用户所说的内容。我只需要保存变量。我避免使用全局变量Python2.7在不再次运行函数中的内容的情况下从函数中获取返回值?,python,function,return,Python,Function,Return,我正在尝试获取函数的返回值。。但我不希望该函数再次运行。这是语音识别,因此,每次它再次运行时,它都会尝试查看用户所说的内容。我只需要保存变量。我避免使用全局变量 def voiceRecognition(self): <A bunch of voice recognition stuff here> return whatUserSaid SPEECH and self的原因是b/c,它是类的一部分,我在另一个Python文件中调用它。现在它正在工作。。。我只需要返
def voiceRecognition(self):
<A bunch of voice recognition stuff here>
return whatUserSaid
SPEECH and self的原因是b/c,它是类的一部分,我在另一个Python文件中调用它。现在它正在工作。。。我只需要返回变量whatUserSaid,而不是让函数重新运行它所做的事情来获取值。我如何做到这一点?根据您给定的代码,看起来您已经将其构建到一个类中,因此我将对此进行一些假设
class VoiceRecognizer(object):
def __init__(self, *args, **kwargs):
self.last_phrase = None
def voiceRecognition(self):
# your code here
self.last_phrase = whatUserSaid
return whatUserSaid
这应该可以让您执行以下操作:
v = VoiceRecognizer()
v.voiceRecognition()
v.last_phrase # is the last return of voiceRecognition
但我不确定你为什么要这么做。你不能把它保存到一个变量里吗
last_phrase = v.voiceRecognition() # like this?
您可以使用一个类实例并记住该值
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
那么,你的代码在哪里?需要显示一些代码-你知道,当你调用一个函数时,你可以将它赋给一个变量-如果你想避免全局变量,那么你需要考虑类。我们需要在你调用该函数时看到代码!很抱歉,我刚刚更新了它。当你第一次在
recognize
方法中添加新内容时,你的递归将失败得太深。我花了一分钟才意识到你在说什么——我们都错了。代码可能会出错,但带有NameError:未定义全局名称“识别”
。我打算调用现有的recognize
——而不是self.recognize
——因此我将其重命名为recognize\u函数。。。非常感谢。我不能这么做,因为我使用的模块完全是垃圾。实际上,我不得不对它进行一些编辑,甚至使它工作起来。
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