“UnboundLocalError:局部变量‘X’分配之前引用”但它是一个全局变量[复制]

问题描述 投票:0回答:1

这个问题已经在这里有一个答案:

我想提出一个Python的不和谐机器人与discord.py。我是比较新的Python的,但有八年左右的与其他语言的经验。我的问题是,我得到即使我已经UnboundLocalError: local variable 'prefix' referenced before assignment定义为全局变量prefix。 (我使用Python 3.6.8)

我曾尝试定义on_ready函数外部变量,但我得到了相同的结果。

import discord;

client = discord.Client();

@client.event
async def on_ready():
  print('Loading complete!')
  ...
  global prefix
  prefix = 'hello world'

@client.event
async def on_message(message):

  if message.author == client.user:
    return

  messageContents = message.content.lower()
  splitMessage = messageContents.split()
  try:
    splitMessage[0] = splitMessage[0].upper()lower()
  except:
    return
  if splitMessage[0]==prefix:
    ...
    (later in that if statement and a few nested ones)
    prefix = newPref

client.run('token')

我预计产量将是它的if语句中运行的代码,而是我得到的错误UnboundLocalError: local variable 'prefix' referenced before assignment并没有代码运行。

我能想到的是这一问题的唯一的事情就是prefix = newpref。我试过了:

global prefix
prefix = newpref

但后来我得到了错误:SyntaxError: name 'prefix' is used prior to global declaration和机器人根本不启动。我该怎么办?

python variables global local discord.py
1个回答
2
投票

按照official docs

这是因为当你进行分配,以在作用域的变量,该变量成为局部的范围和阴影在外部范围的任何类似的命名变量。

简洁版本:

需要声明的你的职责范围,如您之外的全局变量

#declaring the global variable
x = 10
def foobar():
    #accessing the outer scope variable by declaring it global
    global x
    #modifying the global variable
    x+=1
    print(x)
#calling the function
foobar()

龙版本:

基本上,一切都在蟒蛇是一个对象,这些对象的集合称为namespaces

每个模块都有自己的专用符号表,被用作由模块中定义的所有功能全局符号表。因此,模块作者可以在模块中使用全局变量,不会因为与用户的全局变量冲突而引发。

所以,当你运行你的机器人脚本,蟒蛇把它当作运行为主脚本模块,与其自身的全球范围。 当您在全局范围内声明一个变量,使用它的某些功能本地范围,你需要使用关键字global来访问你的模块的全球范围。

此外,蟒蛇不需要分号终止语句(如client = discord.Client();)。分号可以用来分隔语句,如果你希望把多个语句放在同一行。

© www.soinside.com 2019 - 2024. All rights reserved.