在Python上的类中动态装饰方法

时间:2013-03-22 16:21:02

标签: python dynamic decorator

我正在考虑为类创建一个装饰器,它可以动态地将装饰器添加到以特定单词开头的特定方法,而不是手动将装饰器添加到每个方法。

知道怎么做吗?

1 个答案:

答案 0 :(得分:2)

下面的代码示例显示了如何执行此操作:

def class_dec(starts_with,fun_dec):
    def fun(cls):
        for k,v in cls.__dict__.items():
            if k.startswith(starts_with):
                cls.__dict__[k] = fun_dec(v)
        return cls
    return fun

def fun_decorator(f):
    def dec(*args,**kwargs):
        print "I m decorating"
        f(*args,**kwargs)
    return dec

@class_dec("name",fun_decorator)
class Hello:
    def name_new_one(self):
        print "new one"

    def name(self):
        print "Hello"

h = Hello()
h.name()
h.name_new_one()
相关问题