我一直在使用以下(Jython 2.7)代码来装饰某些类中的函数:
import sys
import inspect
from decorator import decorator
def useless_decorator(method, *args, **kwargs):
#Does nothing yet :D
return method(*args, **kwargs)
class UselessMetaClass(type):
def __new__(cls, clsname, bases, dict):
for name, method in dict.items():
if not name.startswith('_') and inspect.isroutine(method):
dict[name] = decorator(useless_decorator, method)
return type.__new__(cls, clsname, bases, dict)
class Useless(object):
__metaclass__ = UselessMetaClass
目标是用useless_decorator
修饰所有公共函数(即名称不以下划线开头的函数)。当然,只有在继承自Useless
的类中才需要这种行为。
不幸的是,我遇到了元类冲突错误。我在调试它们时遇到了很大的困难,我认为它们的出现是由于我无法控制的原因(由于我使用的第三方库:Sikuli)。
但是,也许我根本不需要使用元类!有人知道在不使用元类的情况下模拟我上面的代码的方法吗?
例如,有没有其他方法可以将decorator应用于类中的所有函数?
(附言:我知道我可以手动装饰每个函数,但这不是我想要的解决方案)
将元类转换为类装饰器应该是直接的。类装饰器模拟地接收类作为参数,并返回(修改的)类:
def useless_class_decorator(cls):
for name, method in cls.__dict__.items():
if not name.startswith('_') and inspect.isroutine(method):
setattr(cls, name, decorator(useless_decorator, method))
return cls
这里的主要区别是,您不能直接更改这里的cls.__dict__
,因为对于将成为不支持赋值的dictproxy的新样式类,所以您必须在类上使用setattr
。然后你只需创建你的类:
@useless_class_decorator
class Useless(object):
def method_to_decorate(self, *args, *kwargs):
...
然而,这不会影响Useless
的子类,它们也必须使用类decorator进行装饰。如果这是不可接受的,那么元类可能是更好的选择。。。