问题描述
我真的不需要这样做,但我只是想知道,是否有一种方法可以将装饰器一般地绑定到类中的所有函数,而不是为每个函数明确声明.
I don't really need to do this, but was just wondering, is there a way to bind a decorator to all functions within a class generically, rather than explicitly stating it for every function.
我想它然后成为一种外观,而不是装饰器,它确实有点奇怪,但是在考虑诸如计时或身份验证之类的东西时,它会很整洁.
I suppose it then becomes a kind of aspect, rather than a decorator and it does feel a bit odd, but was thinking for something like timing or auth it'd be pretty neat.
推荐答案
执行此操作或对类定义进行其他修改的最简单方法是定义一个元类.
The cleanest way to do this, or to do other modifications to a class definition, is to define a metaclass.
或者,只需在类定义的末尾应用装饰器即可:
Alternatively, just apply your decorator at the end of the class definition:
class Something:
def foo(self): pass
for name, fn in inspect.getmembers(Something):
if isinstance(fn, types.UnboundMethodType):
setattr(Something, name, decorator(fn))
对于Python 3,将type.UnboundMethodType替换为types.FunctionType.
For Python 3 replace types.UnboundMethodType with types.FunctionType.
当然,在实践中,您将希望更加有选择地应用装饰器,并且只要要装饰除一种方法外的所有装饰,您就会发现,仅使用传统的装饰器语法会更轻松,更灵活.方式.
In practice of course you'll want to apply your decorator more selectively, and as soon as you want to decorate all but one method you'll discover that it is easier and more flexible just to use the decorator syntax in the traditional way.
这篇关于将装饰器附加到类中的所有功能上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!