Python Design Patterns - composition vs. inheritance
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Nov 16 13:14:53 EST 2007
snewman18 at gmail.com a écrit :
(snip)
> It's hard to apply some of the available
> material's examples to Python since a lot of the documentation I find
> is specific to implementations in lower-level languages and don't
> apply to Python.
Fact is that quite a few design patterns are mostly workaround the
low-level and lack of dynamism of the C++/Java family. In higher-level
dynamic languages like Python, Ruby etc, they are not "patterns", they
are idioms with a good builtin support !-)
> (such as the Strategy pattern?)
The "Strategy" pattern is mostly about delegating (part of) a behaviour
to someone else. As such, it can be found (one way or another) in almost
any language - even in C with function pointers (look at how the C
stdlib sort() function works...).
> My understanding was that using __getattr__ was either called
> delegation or a Command pattern,
Now we have proper computed attributes, __getattr__ is mainly used for
delegation, yes. But some years ago, it was also the way to implement
computed attributes.
(snip)
>> Of course there are just reasons to create such delegation methods - if
>> for example the property/method is of general interest to the Pet, but
>> implemented by means of the owner. But I've got difficulties even to
>> imagine such thing, at least in your actual example.
>
> Yeah, I was struggling to come up with a decent example - a pet's
> address was about the best example of a delegated property I could
> think of. If someone has a better set of objects that make sense, let
> me know and I'll probably feel less foolish asking.
class Forbidden(Exception): pass
class Interceptor(object):
def __init__(self, obj, allow_access):
self.__obj = obj
self.__allow_access = allow_access
def __getattr__(self, name):
if self.__allow_access(self.__obj, name):
return getattr(self.__obj, name)
else:
raise Forbidden
As Carl mentioned, real-life code usually uses more technical objects
than domain objects.
More information about the Python-list
mailing list