[英]How to use the same python decorator for all types of methods/functions?
If I have something like this : 如果我有这样的事情:
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
How should I make that @some_decorator so that it will work on every type of function listed above? 我应该如何使该@some_decorator使其适用于上面列出的每种函数? Basically for now I need that decorator to run some code after the method (close SQLAlchemy session). 基本上现在,我需要装饰器在方法之后运行一些代码(关闭SQLAlchemy会话)。 I had problems making any decorator work with methods that are allready decorated with @staticmethod 我在使所有装饰器使用已经用@staticmethod装饰的方法时遇到问题
As long as you keep the decorators in the order given in your post, a straight-forward implementation of the decorator should just work fine: 只要您按照帖子中给出的顺序排列装饰器,装饰器的简单实现就可以正常工作:
def some_decorator(func):
@functools.wraps(func)
def decorated(*args, **kwargs):
res = func(*args, **kwargs)
# Your code here
return res
return decorated
Note that you cannot do eg 请注意,您不能执行例如
@some_decorator
@staticmethod
def bar(**kwargs):
pass
since a staticmethod
object itself is not callable. 因为staticmethod
对象本身是不可调用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.