python应用装饰器到类中的每个方法,而不检查 [英] python apply decorator to every method in a class without inspect
问题描述
稍微修改的答案将python装饰器应用于类中的方法,可以对类中的每个方法应用装饰器。有没有任何方法来做这个没有检查模块?我一直在试图完成这个使用元类和修改__getattribute__但我不断得到无限递归。从 Python - 使用__getattribute__方法,可以在使用对象的正常类中修复此问题.__ getattribute __(self , 名称)。
Slightly modifying the answer from Applying python decorators to methods in a class, it is possible to apply a decorator to every method in a class. Is there any way to do this without the inspect module? I've been trying to accomplish this using metaclasses and modifying __getattribute__ but I keep getting infinite recursion. From Python - Using __getattribute__ method, this can be fixed in normal classes using object.__getattribute__(self, name). Is there anything equivalent for metaclasses?
推荐答案
定义一个元类,然后在类定义的末尾应用装饰器。 p>
Define a meta class and then just apply decorator at the end of class definition.
class Classname:
def foo(self): pass
for name, fn in inspect.getmembers(Classname):
if isinstance(fn, types.UnboundMethodType):
setattr(Classname, name, decorator(fn))
对于Python 3,只需用 types.FunctionType替换
types.UnboundMethodType
c $ c>
For Python 3 just replace the types.UnboundMethodType
with types.FunctionType.
但是如果你真的不想使用检查比你可以这样做
but if you really don;t wanna use inspect than you can do it like this
import types
class DecoMeta(type):
def __new__(cls, name, bases, attrs):
for attr_name, attr_value in attrs.iteritems():
if isinstance(attr_value, types.FunctionType):
attrs[attr_name] = cls.deco(attr_value)
return super(DecoMeta, cls).__new__(cls, name, bases, attrs)
@classmethod
def deco(cls, func):
def wrapper(*args, **kwargs):
print "before",func.func_name
func(*args, **kwargs)
print "after",func.func_name
return wrapper
class MyKlass(object):
__metaclass__ = DecoMeta
def func1(self):
pass
MyKlass().func1()
输出:
Output:
before func1
after func1
before func1
after func1
注意:它不会装饰staticmethod和classmethod
这篇关于python应用装饰器到类中的每个方法,而不检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!