Python创建局部变量而不是使用全局变量

2024-10-02 02:30:10 发布

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

我正在构建一个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

这可能是一个非常简单的错误,如果是的话,我很抱歉,但我已经为此挠头很久了,似乎不明白为什么

提前谢谢


Tags: 函数代码inmessageforreturnif关系
2条回答

为了更改局部函数中的全局变量,需要使用global语句告诉python该变量是全局变量

在这种情况下,它应该看起来像:

async def targetIdentificator(ctx):
    global targetID
    global targetName
    ....

使用globalkeyword显式告诉Python您在引用函数中的全局变量,如下所示:

async def targetIdentificator(ctx):
    global targetID
    global targetName

    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

相关问题 更多 >

    热门问题