On Feb 20, 12:20 pm, "Gregory PiƱero" <[EMAIL PROTECTED]> wrote: > Need some decorator help. > > I have a class. And I want to add behavior to one of this class's > methods to be run before the class runs the actual method. Is this > what decorators are for? > > So the class I want to work with is string.Template > > Let's say I have this: > from string import Template > a=Template("$var1 is a test") > > def preprocess(var1): > #Real code here will be more complicated, just an example > var1=var1.upper() > > a.substitute(var1="greg") > > So how can I have preprocess run before substitute is run? I want the > user to be able to call a.substitute and have preprocess run > automatically. > > Or is this not what decorators do? I'm trying to avoid subclassing if I can. > > Thanks in advance for the help. > > -Greg
You could just overload Template and put your own version of substitute in there. I'm not sure a decorator is appropriate in this case. Here is an overloading example: [code] from string import Template # this assumes you are only interested in keyword arguments # the form substitute(map) will not work class MyTemplate(Template): def substitute(self,**kwargs): for k,v in kwargs.iteritems(): kwargs[k] = v.upper() return super(MyTemplate,self).substitute(self,**kwargs) if __name__ == "__main__": a = MyTemplate("$var1 is a test") print a.substitute(var1 = "greg") [/code] -- http://mail.python.org/mailman/listinfo/python-list