multiple inheritance of a dynamic list of classes?
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Tue Feb 13 18:33:35 EST 2007
devicerandom at gmail.com a écrit :
> Hi,
>
(snip)
> - is there a better way than using multiple inheritance to plug-in
> dynamically commands in a Cmd command line?
Yes : use composition + delegation. Python makes it easy:
#foo.py
class Commands(object):
def do_this(self,args):
...
def do_that(self,args):
...
#bar.py
class Commands(object):
def do_what(self, args):
...
I've seen I can do it by explicitely import them and using multiple
inheritance:
class MyCli(cmd.Cmd):
def __init__(self, *plugins):
self.plugins = plugins
self._cache = {}
def __getattr__(self, name):
try:
return self._cache[name]
except KeyError:
for plugin in self.plugins:
attr = getattr(plugin, name, None)
if attr is not None:
self._cache[name] = attr
return attr
my_cli = MyCli(foo.Command(), bar.Command())
More information about the Python-list
mailing list