En Thu, 13 Aug 2009 12:50:47 -0300, Evan Kroske <e.kro...@gmail.com> escribió:

I'm trying to use the decorator pattern in a program I'm developing. I want
to create a decorator object that works like the object it's decorating
except for a few functions. However, I'd rather not hard-code all the
identical functionality from the decorated object into the decorator object. Is there a way I can intercept all the attribute and function requests for
the decorator and delegate them to the decorated object?

You may search the list archives for references to "proxy" and "delegation". The term "decorator" has a very specific meaning in Python (as a syntax construct), don't use it in the search.

Is it possible (without inheritance)?

Yes, using delegation. See below.

En Thu, 13 Aug 2009 15:29:04 -0300, Rami Chowdhury <rami.chowdh...@gmail.com> escribió:

Oops, my apologies, it's the __getattribute__ method you want to call on self.decorated (because __getattr__ won't be there unless you define it specifically)
So it should go:

def __getattr__(self, request):
        return self.decorated.__getattribute__(request)

__getattribute__ doesn't exist on old-style classes either. Also, note that very rarely one has to *call* __special__ methods; the code should read:

    def __getattr__(self, request):
        return getattr(self.decorated, request)

but that works *only* for old-style classes, as discussed here [1]. [3] is another approach for new-style classes (maybe not production-ready yet). And this recipe [2] shows how to make the decorated object keep calling methods on the decorator itself.

[1] http://code.activestate.com/recipes/252151/
[2] http://code.activestate.com/recipes/519639/
[3] http://code.activestate.com/recipes/496741/

--
Gabriel Genellina

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to