我想实现 decorator pattern在 Python 中,我想知道是否有一种方法可以编写一个只实现它想要修改的函数的装饰器,而无需为所有刚刚转发给装饰对象的函数编写样板。像这样:
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()
关于python - 在 Python 中实现装饰器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3118929/