簡體   English   中英

UnboundLocalError:分配前已引用本地變量“用戶”

[英]UnboundLocalError: Local variable 'user' referenced before assignment

這是在我使用的聊天室中運行主持人機器人的代碼的一部分。 代碼的這一部分是批准某人的請求,但是每當我使用該命令時,我都會收到此未綁定的本地錯誤...我已經經歷了很多次,而且我不知道為什么要得到它。

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])

問題似乎出在“ if user.broadcasting:”

該代碼可在這樣的舊版漫游器上正常工作

def approveCam(room, user):
    if type(user) is str or type(user) is unicode:
        nick = user
        user = room._getUser(user)
    if not user:
        return "User "+nick+" was not found..."

    if not room.bpass:
        return

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

這是我嘗試運行命令時在命令提示符下得到的響應。

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"

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])
user.broadcasting - This is not correct

此時,用戶不存在,因此解釋器不允許這樣做。 您必須先初始化局部變量,然后才能使用它們。

使用戶成為具有某些值的全局變量。

if type(identifier) in [str, unicode, int]:可能為False ,那么if的主體將不會執行,並且user也不會被初始化。

初始化user之前第二if可能的話,或重新考慮你的代碼。

PS不要使用getter和setter! Python不是Java,如果確實需要使用它們,請改用屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM