Delegate attribute requests to object
Rami Chowdhury
rami.chowdhury at gmail.com
Thu Aug 13 12:07:41 EDT 2009
Perhaps I'm misunderstanding something, but I don't think that's really
typical decorator behavior? Typically decorators, as I understand them,
take an instance argument -- so you wouldn't be saying
def __init__(self):
self.decorated = Decorated()
you'd be saying
def __init__(self, decorated):
self.decorated = decorated
As for the attribute access, I believe you can override __getattr__ to do
what you want:
> class Decorator:
> [snip]
> def __getattr__(self, request):
> return self.decorated.__getattr__(request)
The same thing should work for methods, although you may want to pass
arguments through as well.
Is there a reason why, for this use, just making Decorator a subclass of
Decorated (and only overriding the methods you need to be different)
wouldn't work?
On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske <e.kroske at gmail.com> wrote:
> 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? Here's some
> example
> code:
>
> class Decorator:
>> def __init__():
>> self.decorated = Decorated()
>>
>> def newFunction():
>> # Do something
>> pass
>>
>> def interceptRequests(request):
>> return self.decorated.request()
>>
>> class Decorated:
>> def __init__():
>> self.variable = 10
>>
>> def oldFunction():
>> # Do something
>> pass
>
>
> I want to be able to do something like this:
>
> objectA = Decorator()
>> objectB = Decorated()
>> assert objectA.oldFunction() == objectB.oldFunction() # No error
>>
>
> Is it possible (without inheritance)?
>
> --
> Evan Kroske
> http://welcome2obscurity.blogspot.com/
> The code, comments, and challenges of a novice
> software developer desperate for attention.
--
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)
More information about the Python-list
mailing list