object inheritance
Duncan Booth
duncan.booth at invalid.invalid
Fri Oct 26 09:52:39 EDT 2007
Anand <anandology at gmail.com> wrote:
> On Oct 26, 5:31 pm, "Pradeep Jindal" <praddyjin... at gmail.com> wrote:
>> Can you tell any specific use case for doing this?
>
> I have many implementaions of a db interface.
>
> SimpleDB - simple implementation
> BetterDB - optimized implementation
> CachedDB - an implementation with caching of queries
> RestrictedDB - implementation with permissions
>
> Now, I want to combine these implementations and use.
> Typical use case scenarios are:
>
> db = RestrictedDB(CachedDB(SimpleDB()))
> db = RestrictedDB(SimpleDB())
> db = RestrictedDB(BetterDB())
> db = RestrictedDB(CachedDB(BetterDB())
> db = CachedDB(SimpleDB())
> etc..
>
>
No, that is an argument for multiple-inheritance, mixin classes etc. You
know when constructing the object what behaviour you want it to have. It
isn't an argument for changing the behaviour of an existing object
dynamically.
for an example where it is useful to extend the behaviour of objects have a
look at Zope3 interfaces and adaptors: an object can be defined to
implement one or more interfaces, and you can associate additional
interfaces with objects at runtime. Sometimes an object will implement an
interface directly, but often the implementation is taken out into a
separate 'adaptor' class. Whenever you want to use a specified interface on
an object you simply use the interface class as a constructor on the
object, and that might find the appropriate adapter or it might just return
the original object if the interface is provided directly.
e.g. see http://plone.org/documentation/tutorial/five-zope3-walkthrough
Most of the interface/adapter/object relationships in Zope are static, but
there are interfaces which can be added/removed from objects at runtime:
each web accessible object has a page where you can add or remove
interfaces. For example there is an INavigationRoot interface that you can
add to an object which makes it become the top of the navigation tree for
that part of the site or IPhotoAlbumAble which lets an object behave as a
photo album.
Note that this is very different than the forwarding mechanism which
started this thread: when you use an adaptor you get something which
implements just the specified interface, you don't have to worry about
conflicting names for methods or attributes. Also you can have a common
interface associated with objects which have completely different adapters
implementing that interface.
More information about the Python-list
mailing list