Python Design Patterns - composition vs. inheritance

snewman18 at gmail.com snewman18 at gmail.com
Thu Nov 15 15:28:28 EST 2007


In learning about design patterns, I've seen discussion about using
inheritance when an object's relationship to another object is 'is-a'
and composition when the relationship is 'has-a'.

Since this is all new and I'm still learning, I was hoping someone can
give me some pointers on best practices on applying these ideas. If my
logic is incorrect on anything, please don't hesitate to tell me where
I'm wrong - I'm completely open to any help offered.

As a very simplified example, if I had two classes, Pet and Owner, it
seems that I would not have Pet inherit from Owner, since a pet 'has
an' owner, but not 'is an' owner. If this is correct, does my code
below reflect this? I passed the owner object into the pet object's
constructor - is this the right way to do it?

Also, I've seen talk that ideally you shouldn't have too many "dots"
in your method calls, instead using delegates to the methods and
attributes. Can anyone elaborate on this? Ideally, should I be writing
getattr() methods so I can do pet.address instead of
pet.owner.address? Should I be doing the same with owner's methods
like I did with get_foo()?

Thanks in advance to anyone who can share their experience with me -
it's very appreciated.

class Owner(object):
    def __init__(self):
        self.address = '123 Fake Street'

    def get_foo(self):
        return 'bar'

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

    def __getattr__(self, name):
        if name == 'address':
            return self.owner.address
        else:
            raise AttributeError, name

    def get_foo(self):
        return self.owner.get_foo()

owner = Owner()
pet = Pet(owner)



More information about the Python-list mailing list