discord.py中Cog内类方法无法访问类参数如何解决?
问题原因
你两次报错的核心原因都是错误使用了@classmethod装饰器:
@classmethod装饰的方法,第一个传入的参数是类本身,而非类的实例对象- 你代码里的
testMessage是在__init__方法中给实例赋值的属性,只有实例化后的对象才拥有该属性,类本身没有这个属性,所以调用时会抛出AttributeError
第一个场景解决方案
直接去掉sayHello方法的@classmethod装饰器即可,修正后的相关代码:
class TestCog(commands.Cog): def __init__(self): super().__init__() self.testMessage = "hello there" @commands.command(name = 'hello') async def hello(self, ctx): await self.sayHello(ctx) # 移除@classmethod,使用普通实例方法 async def sayHello(self, ctx): await ctx.send(self.testMessage)
第二个场景解决方案
同样去掉TestBot类中sayHello方法的@classmethod装饰器:
class TestBot(commands.Bot): def __init__(self, command_prefix, intents): super().__init__(command_prefix=command_prefix, intents=intents) self.testMessage = "hello there" self.add_cog(TestCog(self)) # 移除@classmethod async def sayHello(self, ctx): await ctx.send(self.testMessage)
额外优化建议
- 你的代码中声明的
client = discord.Client(intents = intents)是冗余代码,commands.Bot本身就是discord.Client的子类,无需额外声明Client实例,可以直接删除该行。 - 如果你确实有使用类方法的需求,需要把
testMessage定义为类属性(直接写在类内部、__init__外部),这样类本身就能访问该属性,但这种方式不适合需要每个实例单独赋值的场景。
内容的提问来源于stack exchange,提问作者Silverhalf
相关产品推荐
相关产品推荐

