UnboundLocalError:在assignmen之前引用了局部变量“user”

2024-04-19 01:12:15 发布

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

这是在我使用的聊天室中运行主持人bot的代码的一部分。这段代码是为了批准某人的请求,但是每当我使用这个命令时,我都会得到这个未绑定的本地错误。。。 我已经经历了这么多次,我不明白为什么我会得到它。在

def approveCam(room, identifier):
    if not room.bpass:
        return

    if type(identifier) in [str, unicode, int]:
        user = room._getUser(identifier)
        if not user:
            return "User " + str(identifier) + " was not found..."

    if user.broadcasting:
        return

    room._sendCommand("privmsg", [room._encodeMessage("/allowbroadcast " + room.bpass),
    "#0,en" + "n" + str(user.id) + "-" + user.nick])

问题似乎出在“如果”用户广播:“

该代码在以前版本的bot上运行,如下所示

^{pr2}$

下面是我在命令提示符下运行命令时得到的响应。在

Traceback (most recent call last):
 File "C:\Users\Ejah\Downloads\Desktop\Tunebot-Master\tinychat.py", line     1262
in onMessage
  SETTINGS['onMessageExtend'](self, user, msg)
 File "tunebot.py", line 1316, in onMessageExtended
  handleUserCommand(room, user, msg)
 File "tunebot.py", line 1722, in handleUserCommand
  res = botterCommands(room, userCmd, userArgsStr, userArgs, target,
 File "tunebot.py", line 2786, in botterCommands
  res = approveCam(room, user)
 File "tunebot.py", line 4043, in approveCam
  if user.broadcasting:
UnboundLocalError: local variable 'user' referenced before assignment"

Tags: 代码inpyreturnifbotlinenot
3条回答

{{{cd4}可能没有被执行。在

如果可能,在第二个if之前初始化user,或者重新考虑代码。在

注意:不要使用getter和setter!Python不是Java,如果您真的需要使用它们,请改用属性。在

user.broadcasting - This is not correct

此时用户不存在,因此解释器不允许这样做。在使用局部变量之前,必须先初始化它们。在

使用户成为一个具有某些值的全局变量。在

更新您的代码以在identifier为无效类型时引发错误,所有这些都将变得清晰:

def approveCam(room, identifier):
    if not room.bpass:
        return

    if type(identifier) in [str, unicode, int]:
        user = room._getUser(identifier)
        if not user:
            return "User " + str(identifier) + " was not found..."
    else:
        raise ValueError('Invalid type for identifier')

    if user.broadcasting:
        return

    room._sendCommand("privmsg", [room._encodeMessage("/allowbroadcast " + room.bpass),
        "#0,en" + "n" + str(user.id) + "-" + user.nick])

相关问题 更多 >