' UnboundLocalError: local variable 'command' referenced before assignment '
' UnboundLocalError: local variable 'command' referenced before assignment '
我正在制作一个可以识别用户语音的麦克风 class。它给了我一个 UnboundLocalError
。当我将 return command
添加到 mic_config()
方法时会发生这种情况。
import speech_recognition as sr
import pyaudio
from speaker import Speaker
class Microphone:
"""Microphone class that represent mic and get user's voice..."""
def __init__(self):
"""Initializing of class"""
self.recognizer = sr.Recognizer() # Voice recognizer
self.microphone = sr.Microphone() # Mic
def mic_config(self):
try:
with self.microphone as source: # Getting mic
print('Listening...')
voice = self.recognizer.listen(source)
command = self.recognizer.recognize_google(voice, language='en-IN') # Using google api
print(command)
except:
pass
return command
m1 = Microphone() # just a test
m1.mic_config()```
是的,正如 Carcigenicate 所说,这是因为命令仅在 try 块中定义。这意味着如果出现错误,则未定义命令。我不知道它是否只是在你在这里发布的代码中,但是 with 语句中有一个缩进错误
try:
with self.microphone as source:
print('Listening...')
voice = self.recognizer.listen(source)
command = self.recognizer.recognize_google(voice, language='en-IN')
print(command)
except:
raise CustomError
# or return None, command = None, etc just define command before the last line
# or don't let the function reach the return command statement
return command
我正在制作一个可以识别用户语音的麦克风 class。它给了我一个 UnboundLocalError
。当我将 return command
添加到 mic_config()
方法时会发生这种情况。
import speech_recognition as sr
import pyaudio
from speaker import Speaker
class Microphone:
"""Microphone class that represent mic and get user's voice..."""
def __init__(self):
"""Initializing of class"""
self.recognizer = sr.Recognizer() # Voice recognizer
self.microphone = sr.Microphone() # Mic
def mic_config(self):
try:
with self.microphone as source: # Getting mic
print('Listening...')
voice = self.recognizer.listen(source)
command = self.recognizer.recognize_google(voice, language='en-IN') # Using google api
print(command)
except:
pass
return command
m1 = Microphone() # just a test
m1.mic_config()```
是的,正如 Carcigenicate 所说,这是因为命令仅在 try 块中定义。这意味着如果出现错误,则未定义命令。我不知道它是否只是在你在这里发布的代码中,但是 with 语句中有一个缩进错误
try:
with self.microphone as source:
print('Listening...')
voice = self.recognizer.listen(source)
command = self.recognizer.recognize_google(voice, language='en-IN')
print(command)
except:
raise CustomError
# or return None, command = None, etc just define command before the last line
# or don't let the function reach the return command statement
return command