函数采用1个位置参数,但给出了2个位置参数

2024-04-24 12:54:23 发布

您现在位置:Python中文网/ 问答频道 /正文

看了其他答案,但似乎没有一个与我的答案相关

我得到一个错误,告诉我我的函数接收的是两个位置参数而不是一个,我无法理解这是如何发生的,因为ctx是唯一的参数

代码:

@commands.command()
  async def join(self, ctx):
    if ctx.author.voice is None:
      await ctx.send("You are not in a voice channel.\nJoin one to use me!")
    voice_channel= ctx.author.voice.channel
    if ctx.voice_client is None:
      await voice_channel.connect()
      await ctx.send("Hello!")
      self.musiccontrols(ctx)
    else:
      await ctx.voice_client.move_to(voice_channel)
      self.musiccontrols(ctx)
async def musiccontrols(ctx):
    newmusicchannel = await ctx.guild.create_text_channel("🎛{}'s Music Controls".format(ctx.author.voice.channel))
    songthumbnail = info['thumbnail']
    songembed=discord.Embed(title="{}'s Music Controls".format(ctx.author.voice.channel), description="", color=000000)
    songembed.set_image(url=songthumbnail)
    if queue is None:
      nowplaying = "Nothing is playing"
    else:
      nowplaying = queue[0]
    songembed.add_field(name="Now Playing:", value=nowplaying, inline=False)
    await newmusicchannel.send(embed=musiccontrolsembed)

错误:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: musiccontrols() takes 1 positional argument but 2 were given
//above referencing line where 
[if ctx.voice_client is None:
      await voice_channel.connect()
      await ctx.send("Hello!")
      self.musiccontrols(ctx)]

Tags: 答案selfclientnonesendifischannel
3条回答

这里有两件事不对:

  1. 你错过了self
  2. 你不是在await协同程序
async def musiccontrols(self, ctx):
    ...
await self.musiccontrols(ctx)

据我所知,这是一个类方法

Python隐式地将self传递给类方法

所以你的电话:

self.musiccontrols(ctx)

实际上变成了:

musiccontrols(self, ctx)

这就是Python抱怨传递了两个参数的原因

修复方法是将函数定义更改为:

async def musiccontrols(self, ctx):

您将musiccontrols称为self.musiccontrols(ctx)的事实表明musiccontrols是一个类方法。在这种情况下,每个类方法的第一个参数都是对类本身的引用。所以试着把async def musiccontrols(ctx):改成async def musiccontrols(self, ctx):

相关问题 更多 >