我正在构建一个Discord机器人,但我认为这与Python的关系比与discord.py
的关系更大
我有此功能,用于识别服务器成员:
async def targetIdentificator(ctx):
targetArgument = ctx.message.content.lower().replace(">target", "")
for member in ctx.message.guild.members:
if targetArgument.lower() in member.name.lower():
targetID = member.id
targetName = targetArgument
print("targetID")
if targetID != "":
return targetID
else:
return None
在代码的上面大约200行,我定义了两个变量:
targetName = ""
targetID = ""
在整个代码中,在各种其他函数中,我已经多次使用这些变量。在这个函数中,当我提到targetID
时,它引用了一个新的局部变量,而不是全局变量。因此,如果for
循环中的if
语句从未通过,我会得到以下错误:
UnboundLocalError: local variable 'targetID' referenced before assignment
这可能是一个非常简单的错误,如果是的话,我很抱歉,但我已经为此挠头很久了,似乎不明白为什么
提前谢谢
为了更改局部函数中的全局变量,需要使用
global
语句告诉python该变量是全局变量在这种情况下,它应该看起来像:
使用
global
keyword显式告诉Python您在引用函数中的全局变量,如下所示:相关问题 更多 >
编程相关推荐