[英]Variable not defined even using global python
PYTHON Just started working with cogs in discord.py so I was copying my code around into cogs but one thing that worked before isn't working in a cog and I cannot figure out why. PYTHON 刚开始在 discord.py 中使用 cogs,所以我正在将我的代码复制到 cogs 中,但之前有效的一件事在 cog 中不起作用,我无法弄清楚为什么。 Code sample below.
下面的代码示例。
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)
Currently the error I am getting is目前我得到的错误是
line 19, in on_message
sverify_index += 1
NameError: name 'sverify_index' is not defined
Please help.请帮忙。
Based on the indentation and the existence of self
, I think you have something like基于缩进和
self
的存在,我认为你有类似的东西
class Something...:
sverify_index=0
sverify_msg_id=""
@commands.Cog.listener()
async def on_message(self, message):
...
That will make sverify_index
and sverify_msg_id
class-level variables (shared by all instances of Something...
), not global variables.这将使
sverify_index
和sverify_msg_id
类级变量(由Something...
的所有实例共享),而不是全局变量。
If you truly want them to be global variables, you can do如果你真的希望它们成为全局变量,你可以这样做
sverify_index = 0
sverify_msg_id = ""
class Something...:
@commands.Cog.listener()
async def on_message(self, message):
global sverify_index, sverify_msg_id
to make them real global variables.使它们成为真正的全局变量。
As AKX mentioned, they are defined class-level variables currently.正如 AKX 提到的,它们目前是定义的类级变量。 In order to have them as global variables, they can be moved out of the class.
为了将它们作为全局变量,可以将它们移出 class。
Since the question was not about making them global variables, but why they are not accessible when moved to a class, another solution can be to keep them as class-level variables, and then access them like self.sverify_index
and self.sverify_msg_id
.由于问题不在于使它们成为全局变量,而是为什么在移动到 class 时无法访问它们,另一种解决方案是将它们保留为类级变量,然后像
self.sverify_index
和self.sverify_msg_id
一样访问它们。
So the solution will be as follows所以解决方案如下
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.