Python变量存在未定义?



我在创建一个简单的开/关开关时遇到了麻烦。我是初学者,我正在写一个不和谐机器人的乐趣和学习。我的机器人在不止一台服务器上,这就是为什么全局变量不是一个选项(在一台服务器上运行它也会为其他服务器改变它)。在命令中放入变量不是一个选项,因为每次运行命令时,它都会定义它。我需要一些存在但只能由子进程定义的东西。

@bot.command()
async def xxx(ctx):
# global x # doesn't work correctly
# x = "" # doesn't work correctly
if x != True:
x = True
await ctx.send("X is on!")

else:
x = False
await ctx.send("X is off!")

while x == True:
#some code calculations here, blablabla
await asyncio.sleep(60)
我的问题的解决方案是什么?谢谢你。

我假设server意味着ctx.guild-所以你可以使用字典来保存不同服务器的值-x[ctx.guild.name]x[ctx.guild]

你不需要在一开始就创建所有的服务器,但是如果服务器在字典中,你可以检查函数并添加默认值。

# global dictionary
x = dict()
@bot.command()
async def xxx(ctx):
# dictionary doesn't need `global x` in function
server_name = ctx.guild.name

# set default value if used first time on server/guild
if server_name not in x:
x[server_name] = False

if not x[server_name]:
x[server_name] = True
await ctx.send("X is on!")
else:
x[server_name] = False
await ctx.send("X is off!")
while x[server_name]:
#some code calculations here, blablabla
await asyncio.sleep(60)

您也可以使用not切换True/False

x[server_name] = not x[server_name]
if x[server_name]:
await ctx.send("X is on!")
else:
await ctx.send("X is off!")

你必须将开关设置在起始位置。你怎么做取决于你自己。我会亲自创建一个转换班。简单的解决方案是在函数外部全局设置起始位置。例子:

global x
x = 0
@bot.command()
async def x(ctx):
if x != True:
x = True
await ctx.send("X is on!")

else:
x = False
await ctx.send("X is off!")
while x == True:
#some code calculations here, blablabla
await asyncio.sleep(60)

您可以尝试将此代码包装在对象中,并将X声明为类变量IE

class ChatBot(object):
x = False
@classmethod
@bot.command()
def xxx(ctx):
if x != True:
x = True
await ctx.send("X is on!")
else:
x = False
await ctx.send("X is off!")

while x == True:
#some code calculations here, blablabla
await asyncio.sleep(60)

面向对象编程使许多事情在python中更容易实现和调试,并且不需要担心全局(除非你绝对需要,否则最好避免单例)。祝你好运——从长远来看,为变量和函数命名也很重要,所以我建议你尽早养成习惯!

相关内容

最新更新