Implementing the decorator pattern in Python

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

    As an addendum to Philipp's answer; if you need to not only decorate, but preserve the type of an object, Python allows you to subclass an instance at runtime:

    class foo(object):
        def f1(self):
            print "original f1"
    
        def f2(self):
            print "original f2"
    
    
    class foo_decorator(object):
        def __new__(cls, decoratee):
            cls = type('decorated',
                       (foo_decorator, decoratee.__class__),
                       decoratee.__dict__)
            return object.__new__(cls)
    
        def f1(self):
            print "decorated f1"
            super(foo_decorator, self).f1()
    
    
    u = foo()
    v = foo_decorator(u)
    v.f1()
    v.f2()
    print 'isinstance(v, foo) ==', isinstance(v, foo)
    

    This is a bit more involved than strictly necessary for your example, where you know the class being decorated in advance.

    This might suffice:

    class foo_decorator(foo):
        def __init__(self, decoratee):
            self.__dict__.update(decoratee.__dict__)
    
        def f1(self):
            print "decorated f1"
            super(foo_decorator, self).f1()
    

提交回复
热议问题