object inheritance

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Nov 1 03:23:09 CET 2007


En Wed, 31 Oct 2007 19:26:17 -0300, Anand <anandology at gmail.com> escribió:

> On Oct 31, 9:57 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> 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




More information about the Python-list mailing list