Python Design Patterns - composition vs. inheritance

snewman18 at gmail.com snewman18 at gmail.com
Thu Nov 15 17:10:26 EST 2007


> Yes. Of course there are other ways, establishing the connection later,
> and of course making the Owner know her pets. But your unidirectional,
> ctor-passed implementation is sensible.

I think my main concern while getting my toes wet on this was to not
reference the owner object out of "thin air" but to pass it in when
pet is instantiated. I'm not sure what 'actor-passed' is yet, but it
gives me something to search for and learn about.

I'd love to see other/better/different implementations if anyone wants
to enlighten me. What would a non-unidirectional (bidirectional?) look
like or accomplish? Does that mean that in the example I provided, you
could make the owner aware of their pets? That's something that is not
available using inheritance, if I understand correctly.

> No, that's certainly not a good idea. And I'm under the impression you
> misunderstood something there in the original lecture/explanation.

That wouldn't surprise me if I misunderstood it :) I've watched Alex
Martelli's Google Tech talk a half-dozen times and it's only now
starting to make sense. 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. (such as the Strategy pattern?)

My understanding was that using __getattr__ was either called
delegation or a Command pattern, and this was hiding/encapsulating the
specifics of the implementation. I'd like to be corrected if I'm
wrong, or if I'm two blocks off Main Street with this.

> The reason is simple: by adding these methods, you essentially extend
> Pet's knowledge as a class to what only its owner has to know. Which
> makes no sense. Why should pets know about addresses? Or cars? Or
> anything else that belongs to the owner only.

> 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.

Thanks for your help! It's truly appreciated.

Scott




More information about the Python-list mailing list