Python 在类中应用decorator all函数而不使用元类

Python 在类中应用decorator all函数而不使用元类,python,python-2.7,jython,jython-2.7,Python,Python 2.7,Jython,Jython 2.7,我一直在使用以下(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__(cl

我一直在使用以下(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
我们的目标是用
无用的\u decorator
装饰所有公共函数(即名称不以下划线开头的函数)。当然,这种行为只在继承自
无用的
的类中出现

不幸的是,我遇到了元类冲突错误。我在调试它们时遇到了很大的困难,我认为它们的出现是出于我无法控制的原因(由于我使用的第三方库:Sikuli)

但是,也许我根本不需要使用元类!有人知道不使用元类模拟我上面代码的方法吗

也就是说,有没有其他方法可以将装饰器应用于类中的所有函数


(另外,我知道我可以手动修饰每个函数,但这不是我想要的解决方案)

将元类转换为类修饰器应该是很简单的。类装饰器简单地接收类作为参数,并返回(修改的)类:

这里的主要区别是,您不能直接更改
cls.\uuu dict\uuuu
这里的新样式类将是不支持赋值的dictproxy,因此您必须在类上使用
setattr
。然后您只需创建您的类:

@useless_class_decorator
class Useless(object):
    def method_to_decorate(self, *args, *kwargs):
        ...
但是,这不会影响无用的子类,这些子类也必须使用类装饰器进行装饰。如果这是不可接受的,那么元类可能是更好的选择

@useless_class_decorator
class Useless(object):
    def method_to_decorate(self, *args, *kwargs):
        ...