在 Python 中实现装饰器模式 [英] Implementing the decorator pattern in Python
本文介绍了在 Python 中实现装饰器模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 Python 中实现 装饰模式,不知道有没有办法编写一个装饰器来实现它想要修改的函数,而不需要为所有刚刚转发给被装饰对象的函数编写样板文件.像这样:
I want to implement the decorator pattern in Python, and I wondered if there is a way to write a decorator that just implements the function it wants to modify, without writing boiler-plate for all the functions that are just forwarded to the decorated object. Like so:
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
?
I would like to have calls to foo_decorator.f2
forwarded to decoratee.f2
automatically. Is there a way to write a generic method that forwards all unimplemented function-calls to 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 中实现装饰器模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文