将装饰器附加到类中的所有函数 [英] Attaching a decorator to all functions within a class

查看:27
本文介绍了将装饰器附加到类中的所有函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不需要这样做,但只是想知道,是否有一种方法可以将装饰器一般地绑定到类中的所有函数,而不是为每个函数显式声明它.

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 using inspect:

import inspect

class Something:
    def foo(self): 
        pass

for name, fn in inspect.getmembers(Something, inspect.isfunction):
    setattr(Something, name, decorator(fn))

在实践中,您当然希望更有选择地应用您的装饰器.一旦您想装饰除一种方法之外的所有方法,您就会发现仅以传统方式使用装饰器语法更简单、更灵活.

In practice of course you'll want to apply your decorator more selectively. 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.

这篇关于将装饰器附加到类中的所有函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆