【问题标题】:How to use the same python decorator for all types of methods/functions?如何对所有类型的方法/函数使用相同的 python 装饰器?
【发布时间】:2012-02-20 16:18:14
【问题描述】:

如果我有这样的事情:

class SomeClass(object):

    @classmethod
    @some_decorator
    def foo(cls, **kwargs):
        pass

    @some_decorator
    def bar(self, **kwargs):
        pass

    @staticmethod
    @some_decorator
    def bar(**kwargs):
        pass

@some_decorator
def function_outside_class(**kwargs):
    pass

我应该如何制作 @some_decorator 以便它适用于上面列出的每种类型的功能?基本上现在我需要那个装饰器在方法之后运行一些代码(关闭 SQLAlchemy 会话)。我在让任何装饰器使用已经用 @staticmethod 装饰的方法时遇到问题

【问题讨论】:

    标签: python decorator python-2.7


    【解决方案1】:

    只要您按照帖子中给出的顺序保持装饰器,装饰器的直接实现应该可以正常工作:

    def some_decorator(func):
        @functools.wraps(func)
        def decorated(*args, **kwargs):
            res = func(*args, **kwargs)
            # Your code here
            return res
        return decorated
    

    请注意,您不能这样做,例如

    @some_decorator
    @staticmethod
    def bar(**kwargs):
        pass
    

    因为 staticmethod 对象本身是不可调用的。

    【讨论】:

    • 您是否愿意根据此粘贴扩展 staticmethod 不可调用的对象?我相信你是对的,但我认为这种说法很容易被误解。 pastebin.com/TUr3g3i0
    • @Marcin 你需要调用 Foo.foo 作为像 Foo.foo() 这样的方法,如果这是你想要的。
    • @Sven Marnach 我很确定我已经尝试过这种方式,但是明天当我用那个代码回到 PC 时我会再次检查它,也许我犯了一些愚蠢的错字..
    • @SašaŠijak:我不确定你的意思 - 在这两种情况下,调用都很好。问题在于 staticmethod 对象。
    • @Marcin:staticmethod 对象是一个描述符。使用Foo.foo 检索它时,您将获得一个可调用对象。当您以vars(Foo)["foo"] 访问它时,您将获得staticmethod 对象本身。后者是 not 可调用的,这就是外部装饰器在最后一个代码 sn-p 中看到的内容。
    猜你喜欢
    • 2021-04-16
    • 2010-11-20
    • 2020-11-30
    • 2017-10-21
    • 2017-03-13
    • 2011-08-20
    • 1970-01-01
    • 2016-04-29
    • 2012-09-03
    相关资源
    最近更新 更多