使用导入文件的变量

Use variables of imported files

所以我有这个文件,代码如下

async def check_server_restriction(ctx):
    restriction = await get_restriction()
    global check
    
    if restriction[str(ctx.channel.id)]["Server"] == 1:
        await ctx.send("This command is restricted. You can use it in the #bot-commands channel")
        check = True

我还有另一个文件,如下所示:

from channel_restrictions_functions import test_187, new_restriction, get_restriction, check_server_restriction, check
class whois(commands.Cog):

    def __init__(self, client):
        self.client = client


    @commands.command()
    async def whois(self, ctx, member:discord.Member = None):
        await test_187()
        await new_restriction(ctx)
        await check_server_restriction(ctx)
        
        #print(check)
        if check == True:
            print("Nicht perint")
            return

所以基本上我导入函数并尝试导入变量。现在的问题是当导入的函数被激活并检查(变量)True(理论上)没有任何反应。当事物在列表中时,它应该像这样工作,它应该发送“此命令受限”并设置检查为真,以便在我的命令中 if 语句有效并且它将 return.

我不明白这是怎么回事。我认为它每次都说 check = False 但它应该是 true

我希望你能理解我的问题并且知道如何解决它 谢谢你的帮助

即使是全局变量也不是真正全局的,它们只在自己的模块范围内是全局的。有一些方法可以绕过这个限制并在模块之间共享一个变量,如果你绝对需要,请参见例如here. It is recommended to put all global variables into a separate module and import from there, however, see the Python docs 了解更多。


就是说,您为什么要使用全局变量来执行此操作?它更简单,更不容易出错(从某种意义上说,如果是全局的,限制状态将在命令之间共享,这可能导致命令被错误地限制)只有 check_server_restriction return TrueFalse 然后检查函数的 return 值,如下所示:

async def check_server_restriction(ctx):
    restriction = await get_restriction()
    
    if restriction[str(ctx.channel.id)]["Server"] == 1:
        await ctx.send("This command is restricted. You can use it in the #bot-commands channel")
        return True
    return False

在您的代码中,您将像这样使用这个修改后的函数:

if await check_server_restriction(ctx):  # the == True can be omitted
    print("Nicht perint")
    return