首页 > 解决方案 > 使用 discord.py 从另一个 cog 导入函数

问题描述

我想从另一个 cog 导入一些函数,以便它们可以用于不同 .py 文件中的多个 cog。我该怎么做呢?这是文档中的内容:

class Economy(commands.Cog):
    ...

    async def withdraw_money(self, member, money):
        # implementation here
        ...

    async def deposit_money(self, member, money):
        # implementation here
        ...

class Gambling(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    def coinflip(self):
        return random.randint(0, 1)

    @commands.command()
    async def gamble(self, ctx, money: int):
        """Gambles some money."""
        economy = self.bot.get_cog('Economy')
        if economy is not None:
            await economy.withdraw_money(ctx.author, money)
            if self.coinflip() == 1:
                await economy.deposit_money(ctx.author, money * 1.5)

举个例子,但这意味着economy如果我想调用它,我必须每次都定义。有没有更有效的方法来调用另一个 cog 中的函数?

标签: pythonclassdiscorddiscord.py

解决方案


如果withdraw_money并且deposit_money不使用任何Economy's 属性或方法,您可以将它们设为静态方法并导入Economy以使用它们,或者只是使它们在类/cog 之外起作用并直接导入它们。

否则,您可以寻找一种方法来重构这些方法,使它们不依赖于它们,Economy以便您可以使它们成为静态方法或独立函数。

如果这不可能,这已经是最好的方法了。
Bot.get_cog无论如何都是 O(1),所以对效率的影响非常小。


推荐阅读