2

我一直在使用以下(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)。

但是,也许我根本不需要使用元类!有谁知道在不使用元类的情况下模拟我上面的代码的方法?

IE,有没有其他方法可以将装饰器应用于类中的所有函数?

(PS 我知道我可以手动装饰每个功能,但这不是我正在寻找的解决方案)

4

1 回答 1

4

将您的元类转换为类装饰器应该是直截了当的。类装饰器简单地将类作为参数接收并返回(修改后的)类:

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,这些子类也必须使用类装饰器进行装饰。如果这是不可接受的,那么元类可能是更好的选择......

于 2015-03-17T21:25:06.843 回答