【问题标题】:Variable not defined even using global python即使使用全局python也没有定义变量
【发布时间】:2021-11-29 17:30:19
【问题描述】:

Python 刚开始在 discord.py 中使用 cogs,所以我将我的代码复制到 cogs 中,但是之前有效的一件事在 cog 中不起作用,我不知道为什么。下面的代码示例。

    sverify_index=0
    sverify_msg_id=""
    @commands.Cog.listener()
    async def on_message(self, message):
        if message.channel.id == 888529033405530183 and message.author.id != 887542628063780864:
                global sverify_index, sverify_msg_id
                sverify_index += 1
                sverify_list = []
                sverify_list.append(sverify_index)

目前我得到的错误是

line 19, in on_message
    sverify_index += 1
NameError: name 'sverify_index' is not defined

请帮忙。

【问题讨论】:

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


    【解决方案1】:

    基于缩进和self的存在,我认为你有类似的东西

    class Something...:
        sverify_index=0
        sverify_msg_id=""
        @commands.Cog.listener()
        async def on_message(self, message):
             ...
    

    这将使sverify_indexsverify_msg_id 类级变量(由Something... 的所有实例共享),而不是全局变量。

    如果你真的想让它们成为全局变量,你可以这样做

    sverify_index = 0
    sverify_msg_id = ""
    
    class Something...:
        @commands.Cog.listener()
        async def on_message(self, message):
             global sverify_index, sverify_msg_id
    

    使它们成为真正的全局变量。

    【讨论】:

    • 另外,由于它们实际上可能不需要是全局的,因此您可以使用类的名称来限定每个引用。 Something.sverify_index += 1
    • @MarkRansom 实际上,它们可能应该是真正的实例变量,因此 cog 插件的每个实例都有自己的副本...
    【解决方案2】:

    正如 AKX 所提到的,它们目前是定义的类级变量。 为了将它们作为全局变量,可以将它们移出类。

    另一种方法

    由于问题不在于使它们成为全局变量,而是为什么它们在移动到类时无法访问,另一种解决方案是将它们保留为类级变量,然后像 self.sverify_index 和 @987654322 一样访问它们@。

    所以解决办法如下

    class Something(commands.Cog):
        ...
    
        sverify_index=0
        sverify_msg_id=""
        
        @commands.Cog.listener()
        async def on_message(self, message):
            if (message.channel.id == 888529033405530183 and 
                message.author.id != 887542628063780864):
            
                self.sverify_index += 1
                self.sverify_list = []
                self.sverify_list.append(self.sverify_index)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-06
      相关资源
      最近更新 更多