在Python中实现装饰器模式 - 代码日志

在Python中实现装饰器模式

我想在Python中实现decorator pattern,我想知道是否有一种方法可以编写一个只是实现它要修改的功能的装饰器,而不需要为刚转发到装饰对象的所有函数编写锅炉板。像这样:

class foo(object):
    def f1(self):
        print "original f1"
    def f2(self):
        print "original f2"

class foo_decorator(object):
    def __init__(self, decoratee):
        self._decoratee = decoratee
    def f1(self):
        print "decorated f1"
        self._decoratee.f1()
    def f2(self):              # I would like to leave that part out
        self._decoratee.f2()

我想要调用foo_decorator.f2自动转发到decoratee.f2。有没有办法编写将所有未实现的函数调用转发到decoratee的通用方法?

你可以使用__getattr__:

class foo(object):
    def f1(self):
        print "original f1"
    def f2(self):
        print "original f2"

class foo_decorator(object):
    def __init__(self, decoratee):
        self._decoratee = decoratee
    def f1(self):
        print "decorated f1"
        self._decoratee.f1()
    def __getattr__(self, name):
        return getattr(self._decoratee, name)

u = foo()
v = foo_decorator(u)
v.f1()
v.f2()
http://stackoverflow.com/questions/3118929/implementing-the-decorator-pattern-in-python

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:在Python中实现装饰器模式