【问题标题】:Decorator arguments lost in self装饰器参数迷失在自我中
【发布时间】:2021-04-03 13:36:41
【问题描述】:

我有一个装饰器

class Utilities(commands.Cog):
    def has_any_role(self, *items):
        async def predicate(ctx):
            ctx.command.needed_roles = items
            return await commands.has_any_role(*items).predicate(ctx)
        return commands.check(predicate)

    @has_any_role('Owner', 'Moderator')
    @commands.command()
    async def foo(...):
        ...

但是现在当我尝试访问Commands needed_roles 属性时,它只会返回foo 的主持人,因为"Owner" 迷失了自我。我怎样才能解决这个问题而不只是将函数放在类之外?

【问题讨论】:

    标签: python-3.x decorator


    【解决方案1】:

    试试:

    @staticmethod
    def has_any_role(*items)
    ...
    

    【讨论】:

    • 我已经试过了,你不能调用静态方法。与类方法相同
    • 当然——那时它是一个类似描述符的东西。 (您本可以提到您首先尝试过 :-)。无论如何,question 回答了您的问题——基本上,只需在方法定义中省略 self 即可。
    猜你喜欢
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2012-07-25
    • 1970-01-01
    • 2019-06-14
    • 2019-10-21
    • 1970-01-01
    • 2011-06-25
    相关资源
    最近更新 更多