Implementing the decorator pattern in Python

后端 未结 7 1561
梦谈多话
梦谈多话 2020-12-02 09:59

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 writ

7条回答
  •  遥遥无期
    2020-12-02 10:32

    In Python 3, Philipp's accepted answer raised RuntimeError: maximum recursion depth exceeded.

    The way that worked for me:

    class Foo(object):
        def f1(self):
            print("original f1")
    
        def f2(self):
            print("original f2")
    
    class FooDecorator(object):
        def __init__(self, decoratee):
            self._decoratee = decoratee
    
        def f1(self):
            print("decorated f1")
            return self._decoratee.f1()
    
        def __getattr__(self, name):
            if name in ['f1', '_decoratee']:
                raise AttributeError()
            return getattr(self._decoratee, name)
    
    f = FooDecorator(Foo())
    f.f1()
    # decorated f1
    # original f1
    f.f2()
    # original f2
    

    The workaround is inspired by Ned Batchelder's blog

提交回复
热议问题