如何在函数内调用变量 - discord.py

How to call a variable inside a function - discord.py

@bot.command()
async def blackjack(ctx):
    cards = "♣️3"
   
    @bot.event
    async def on_message(msg):
        globals cards
        print(cards)

我在 discord.py 中执行 blackjack 命令,但 运行 出现了变量“cards”未定义的问题(因为它不是局部变量) 我不确定如何解决这个问题。我试过包括“全球卡”,但它仍然没有用。

它无法访问该变量,因为您在单独的方法中定义了它。如果您在这两种方法之外定义变量,那么您的所有方法都可以自由访问和更改变量。

代码

cards = "♣️3"

@bot.command()
async def blackjack(ctx):
    #code here
    pass

@bot.event
async def on_message(msg):
    print(cards)