Python Design Patterns - composition vs. inheritance

Diez B. Roggisch deets at nospam.web.de
Thu Nov 15 23:25:07 CET 2007


> 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 meant ctor, short-hand for constructor.

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


Its simple.

class Owner(object):
     def __init__(self):
         self.pets = []

class Pet(object):
     def __init__(self, owner):
         self.owner = owner
         owner.pets.append(self)



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

I don't know that talk. Maybe you can give us the link, so we can see 
for ourselves?

There is no doubt about Alex' being a profound teacher of software 
design. But yet I think your example doesn't capture what you think he 
wanted to present.

Delegation of course is a well-known pattern. It applies at 
circumstances that are manyfold, e.g. wehn you try create a proxy for 
purposes of tracking or filtering calls.


Diez



More information about the Python-list mailing list