Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用discord.py从另一个cog导入函数_Python_Class_Discord_Discord.py - Fatal编程技术网

Python 使用discord.py从另一个cog导入函数

Python 使用discord.py从另一个cog导入函数,python,class,discord,discord.py,Python,Class,Discord,Discord.py,我想从另一个cog导入一些函数,以便它们可以用于不同.py文件中的几个cog。我该怎么做呢?以下是文档中的内容: class Economy(commands.Cog): ... async def withdraw_money(self, member, money): # implementation here ... async def deposit_money(self, member, money): # i

我想从另一个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)

作为一个例子,但这意味着如果我想调用它,每次我都必须定义
经济。在另一个cog中调用函数是否有更有效的方法?

如果
取款
存款
不使用
经济
的任何属性或方法,您可以使它们成为静态方法并导入
Economy
以使用它们,或者只是使它们成为类/cog之外的函数并直接导入它们

否则,您可以寻找重构这些方法的方法,使它们不依赖于
Economy
,从而使它们成为静态方法或独立函数

如果不可能,这已经是最好的方法了。

Bot.get\u cog
无论如何都是O(1),所以效率方面的影响非常小。

假设文件名为
cog.py
,您可以尝试在要使用
Economy
的文件中再次使用
cog.py,它位于一个名为cogs的文件夹中,结构如下:main.py cogs->cog文件在此尝试以下操作:使用上述导入
经济
本身将无法正常工作,因为
取款
存款
都是实例方法,而初始化cog的另一个版本肯定会比简单地使用Bot.get_cog
获取现有版本效率低得多。您可以尝试在
赌博中设置
经济性。这将使加载COG的顺序变得有意义,如果代码中可能的话,您需要添加逻辑来处理重新加载。