【问题标题】:UnboundLocalError: local variable 'msg' referenced before assignment. How to fix it?UnboundLocalError:分配前引用的局部变量“msg”。如何解决?
【发布时间】:2018-09-05 03:45:25
【问题描述】:

我正在从 json 文件中获取消息计数,但我有一个错误...而且我不知道为什么。在这个程序中,机器人必须发送有关提及成员的信息。如果我在代码开头写msg = None,它不会像> messages = 10那样发送它会发送messages = None

程序

if args[0] == '!in':
    await client.delete_message(message)
    highclass = None
    gm = ""
    clan = None
    if (roleLeaders in message.author.roles or roleHunter in message.author.roles or roleDeputy in message.author.roles):
            for member in message.mentions:
                user = member
                userjoin = str(user.joined_at)
                joinpars= userjoin.split()
                join = joinpars[0]
                msg1 = user_get_msg(member.id)
                time1 = user_get_time(member.id)
                s = str(msg1)
                last = int(s[-1])
                st = str(time1)
                stm = time1 // 60
                sth = stm // 60
                std = sth // 24
                if time1 <= 60:
                    lastt = int(st[-1])
                    if lastt == 0:
                        time = '{0} секунд'.format(time1)
                    if lastt == 1 and not time1 == 11:
                        time = '{0} секунду'.format(time1)
                    if ((time1 >= 11 and time1 <= 19) or (lastt >= 5 and lastt <= 9)):
                        time = '{0} секунд'.format(time1)
                    if (lastt >= 2 and lastt <= 4) and not (time1 >= 11 and time1 <= 19):
                        time = '{0} секунды'.format(time1)

                if time1 <= 3600 and time1 > 60:
                    lastt = int(str(stm)[-1])
                    if lastt == 0:
                        time = '{0} минут'.format(stm)
                    if lastt == 1 and not stm == 11:
                        time = '{0} минуту'.format(stm)
                    if ((stm >= 11 and stm <= 19) or (lastt >= 5 and lastt <= 9)):
                        time = '{0} минут'.format(stm)
                    if (lastt >= 2 and lastt <= 4) and not (stm >= 11 and stm <= 19):
                        time = '{0} минуты'.format(stm)

                if time1 <= 86400 and time1 >3600:
                    lastt = int(str(sth)[-1])
                    if lastt == 0:
                        time = '{0} часов'.format(sth)
                    if lastt == 1 and not sth == 11:
                        time = '{0} час'.format(sth)
                    if ((sth >= 11 and sth <= 19) or (lastt >= 5 and lastt <= 9)):
                        time = '{0} часов'.format(sth)
                    if (lastt >= 2 and lastt <= 4) and not (sth >= 11 and sth <= 19):
                        time = '{0} часа'.format(sth)

                if time1 >= 86400:
                    lastt = int(str(std)[-1])
                    if lastt == 0:
                        time = '{0} дней'.format(std)
                    if lastt == 1 and not std == 11:
                        time = '{0} день'.format(std)
                    if ((std >= 11 and std <= 19) or (lastt >= 5 and lastt <= 9)):
                        time = '{0} дней'.format(std)
                    if (lastt >= 2 and lastt <= 4) and not (std >= 11 and std <= 19):
                        time = '{0} дня'.format(std)
                if msg1 >= 0:
                    if last == 0 or msg1 == 0:
                        msg = '{0} записок'.format(msg1)
                    if msg1 == 1 or (last == 1 and msg1 >= 21):
                        msg = '{0} записку'.format(msg1)
                    if (msg1 >= 2 and msg1 <= 4) or (msg1 >= 22 and msg1 <= 24):
                        msg = '{0} записки'.format(msg1)
                    if (last >= 5 and last <= 9):
                        msg = '{0} записок'.format(msg1)
                for role in member.roles:
                    with open('class.json', 'r') as roleread:
                        if role.id in roleread.read():
                            highclass = '<@&{0}>'.format(role.id)
                    with open('clans.json', 'r') as fp:
                        if role.id in fp.read():
                            gm = '> Является участником гильдии <@&{0}>.'.format(role.id)
                            if roleGM in member.roles:
                                gm = '> Является **мастером** гильдии <@&{0}>.'.format(role.id)
                await asyncio.sleep(0.01)
                await client.send_message(message.channel, 'Персонаж {0}:\n'
                                                           '> Прибыл в город **{1}**;\n'
                                                           '> Принимал участие в жизни города **{2}**;\n'
                                                           '> Написал **{3}**;\n'
                                                           '> Имеет класс {4};\n'
                                                           '{5}'.format(member.mention, join, time, msg, highclass, gm))

错误

File "soul.py", line 497, in on_message
'{5}'.format(member.mention, join, time, msg, highclass, gm))
UnboundLocalError: local variable 'msg' referenced before assignment

我已经尽力了。有人可以帮帮我吗?

【问题讨论】:

  • 这不可能是您的实际代码,因为它甚至在达到那一步之前就引发了SyntaxError。请给我们minimal reproducible example
  • msg1 &gt;= 0: 会抛出一个 SyntaxError 所以我不确定你在这里实际运行什么代码......
  • 稍等
  • 问题在于if 语句。因为没有else 语句,所以您可以通过该部分代码而不将msg 分配给任何东西。老实说,看起来你试图在一个地方做太多事情。尝试将您的代码分解为离散的函数(以及适当的协程)。这样可以更轻松地跟踪您正在做的事情。
  • @PatrickHaugh 我会试试这个

标签: python python-3.x discord discord.py


【解决方案1】:

看看你是如何给msg赋值的:

if last == 0 or msg1 == 0:
    msg = '{0} some useless tex'.format(msg1)
if msg1 == 1 or (last == 1 and msg1 >= 21):
    msg = '{0} some useless tex'.format(msg1)
if (msg1 >= 2 and msg1 <= 4) or (msg1 >= 22 and msg1 <= 24):
    msg = '{0} some useless tex'.format(msg1)
if (last >= 5 and last <= 9):
    msg = '{0} some useless tex'.format(msg1)

那么,如果 msg1 是 10-20 范围内的某个值(并且 last 不是 0)会发生什么?那么这些ifs 都不会触发。所以msg 永远不会被分配任何东西。但无论如何你都会尝试使用它,并得到那个错误。

你可能想要这样的东西:

if last == 0 or msg1 == 0:
    msg = '{0} some useless tex'.format(msg1)
elif msg1 == 1 or (last == 1 and msg1 >= 21):
    msg = '{0} some useless tex'.format(msg1)
elif (msg1 >= 2 and msg1 <= 4) or (msg1 >= 22 and msg1 <= 24):
    msg = '{0} some useless tex'.format(msg1)
elif (last >= 5 and last <= 9):
    msg = '{0} some useless tex'.format(msg1)
else:
    msg = '{0} WARNING! UNEXPECTED VALUE!'.format(msg1)

(请注意,将所有这些 ifs 更改为 elifs 可能是语义上有意义的更改。如果两个条件都为真,则您的原始代码将同时执行它们,因此第二个将覆盖第一次这样做,但新代码只会执行第一个。如果它有所作为,这实际上是你想要的更多 - 但如果你想要其他行为,你可能需要重写或重新排序你的条件。)

【讨论】:

    猜你喜欢
    • 2017-08-10
    • 2020-01-16
    • 2019-12-05
    • 2017-09-19
    • 2020-09-26
    • 2022-01-02
    • 2019-03-22
    • 2019-01-24
    • 2021-07-01
    相关资源
    最近更新 更多