在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屋!
查看全文