當我做我的 discord.py 專案時,我發現以下代碼在第一次運行良好,但第二次(在單次運行中)回傳一個屬性錯誤。
class Test2(commands.Cog):
def __init__(self, dc_bot):
self.bot = dc_bot
self.ui = ""
@commands.command(description="get avatar")
async def getavatar(self, ctx, *, content: str):
avatar = self.bot.user.avatar_url
self.ui = content
await ctx.send(content)
await ctx.send(avatar)
self.__init__(self) # reset the values
第一次效果很好。
第二次它會說:AttributeError: 'Test2' has no attribute 'user'
我猜是因為我想為下一次運行重置 self.ui 。
如果我的 init 函式中有很多“self”需要使用,我認為(之前)只呼叫 init 函式是個好主意。但是self.ui = dc_bot我認為再次運行會導致這個問題。你能解釋一下為什么會發生這種情況嗎?
uj5u.com熱心網友回復:
重新呼叫 init 方法時出現錯誤。self.__init__(self)實際上是在打電話Test2. __init__(self, self) 。self.bot = self當您第二次運行命令時,它會因此覆寫屬性錯誤。相反,您想要:
self.__init__(self.bot)
但這不是一個好的解決方案,相反,您應該有一個“重置”輔助方法來執行重置,并且您呼叫輔助方法而不是 init。因為通常情況下,一旦類啟動,您就不想再次呼叫 init 方法。
uj5u.com熱心網友回復:
你讓代碼太復雜了試試這個!
@commands.command(description = "get avatar")
async def getavatar(self, ctx, *, avamember: discord.Member = None):
userAvatarUrl = avamember.avatar_url
await ctx.send(userAvatarUrl)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/335380.html
