En Wed, 31 Oct 2007 19:26:17 -0300, Anand <[EMAIL PROTECTED]> escribió:
> On Oct 31, 9:57 am, "Gabriel Genellina" <[EMAIL PROTECTED]> > wrote: >> >> If you know at compile time which features you want, you can use >> multiple >> inheritance to define the new class. >> If you only know the set of clases to mix at run time, you can >> dinamically >> create new classes with 'type': > > Interesting. > > CachedDB.withID should call withID from its super class (here > SimpleDB), when it is not in cache. How to do that? Using super(). See <http://docs.python.org/dev/tutorial/classes.html#multiple-inheritance> and <http://www.python.org/2.3/mro.html> for the details. This is a running version of your example: py> class SimpleDB(object): ... def withID(self, id): ... print "SimpleDB.withID",id ... return "Data for %s" % id ... def withIDs(self, ids): ... return [self.withID(id) for id in ids] ... py> class CachedDB(object): ... def __init__(self): ... # CachedDB instances must have a cache dictionary ... super(CachedDB, self).__init__(self) ... self.cache = {} ... def withID(self, id): ... print "CachedDB.withID",id ... res = self.cache.get(id) ... if res is None: ... print "cache miss!" ... self.cache[id] = res = super(CachedDB, self).wit hID(id) ... return res ... py> newclass = type('newclass', (CachedDB, SimpleDB), {}) py> db = newclass() py> print db.withIDs([1,2,1,3,2,1]) CachedDB.withID 1 cache miss! SimpleDB.withID 1 CachedDB.withID 2 cache miss! SimpleDB.withID 2 CachedDB.withID 1 CachedDB.withID 3 cache miss! SimpleDB.withID 3 CachedDB.withID 2 CachedDB.withID 1 ['Data for 1', 'Data for 2', 'Data for 1', 'Data for 3', 'Data f or 2', 'Data for 1'] Multiple inheritance is not the only option. You may want to read about decorators too: instead of overriding the method withID, you can decorate it with some variant of the "memoize" decorator. Look for the (excellent!) article on decorators by Michele Simionato. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list