Implementing the decorator pattern in Python

后端 未结 7 1553
梦谈多话
梦谈多话 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:51

    To complement @Alec Thomas reply. I modified his answer to follow the decorator pattern. This way you don't need to know the class you're decorating in advance.

    class Decorator(object):
        def __new__(cls, decoratee):
            cls = type('decorated',
                       (cls, decoratee.__class__),
                       decoratee.__dict__)
            return object.__new__(cls)
    

    Then, you can use it as:

    class SpecificDecorator(Decorator):
        def f1(self):
            print "decorated f1"
            super(foo_decorator, self).f1()
    
    class Decorated(object):
        def f1(self):
            print "original f1"
    
    
    d = SpecificDecorator(Decorated())
    d.f1()
    

提交回复
热议问题