python - 在 Python 中实现装饰器模式

标签 python design-patterns

我想实现 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/

相关文章:

python - 如何将 BOW 以外的功能添加到 scikit-learn 分类模型中

python - 调用 NLTK 的索引 - 如何在使用的单词之前/之后获取文本?

python - 模块 'networkx' 没有属性 'blockmodel'?

design-patterns - ExtJS 有标准的设计模式吗

java - Java或C#中工厂设计模式的反射(reflection)

Python属性错误: 'module' object has no attribute 'init'

python - 将 neo4django 与 apache 一起使用

ios - 具有多个 TableView 的 Swift MVC 设计

java - 使用 ExecutorService 对管道模式中的一个阶段进行多线程处理

java - 如何访问继承中的私有(private)字段