July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Sébastien Keim
You have classes that need vast numbers of options to be passed to their constructors for configuration purposes. This often happens with GUI toolkits in particular.
We can model the options with a suitable class:
class Options:
def _ _init_ _(self, **kw):
self._ _dict_ _.update(kw)
def _ _lshift_ _(self, other):
""" overloading operator << """
s = self._ _copy_ _( )
s._ _dict_ _.update(other._ _dict_ _)
return s
def _ _copy_ _(self):
return self._ _class_ _(**self._ _dict_ _)and then have all classes using options inherit from the following class:
class OptionsUser:
""" Base class for classes that need to use options """
class OptionError(AttributeError): pass
def initOptions(self, option, kw):
""" To be called from the derived class constructor.
Puts the options into object scope. """
for k, v in option._ _dict_ _.items() + kw.items( ):
if not hasattr(self._ _class_ _, k):
raise self.OptionError, "invalid option " + k
setattr(self, k, v)
def reconfigure(self, option=Options( ), **kw):
""" used to change options during object life """
self.initOptions(option, kw)
self.onReconfigure(self)
def onReconfigure(self):
""" To be overloaded by derived classes. Called by the reconfigure
method or from outside after direct changes to option attributes. """
passTo explain why you need this recipe, let’s start with an example:
class TextBlock: def _ _init_ _ (self, font='Times', size=14, color=(0,0,0), height=0, width=0, align='LEFT', ...
Read now
Unlock full access