[英]How can I use the same parameters in a decorator with that in the functions in Python?
[英]How to use the same python decorator for all types of methods/functions?
如果我有這樣的事情:
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裝飾的方法時遇到問題
只要您按照帖子中給出的順序排列裝飾器,裝飾器的簡單實現就可以正常工作:
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
對象本身是不可調用的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.