Adding method to a class on the fly
John Henry
john106henry at hotmail.com
Sat Jun 23 15:03:05 EDT 2007
On Jun 23, 10:56 am, Steven D'Aprano
<s... at REMOVE.THIS.cybersource.com.au> wrote:
> On Sat, 23 Jun 2007 09:06:36 -0700, John Henry wrote:
>
> >> > But then how do I create the on_Button1_mouseClick function?
>
> >> That depends on what it is supposed to do, but in general you want a
> >> factory function -- a function that returns functions. Here's a simple
> >> example:
>
> > <snip>
>
> > Steven,
>
> > May be I didn't explain it clearly: the PythonCard package expects to
> > see a function by the name of on_Button1_mouseClick. I don't do
> > anything to register the callback function. The package assumes that
> > there is a function by that name whenever I create a button named
> > Button1. So, if I don't use exec, how can I create a function by that
> > exact name?
>
> def mouseclick_factory(name):
> def function(self, event):
> print "You clicked '%s'." % name
> function.name = "on_%s_mouseClick" % name
> return function
>
> class Parrot:
> def __init__(self, name):
> function = mouseclick_factory(name) # as before
> method = new.instancemethod(function, self, self.__class__)
> setattr(self, function.name, method)
>
> And here it is in action:
>
> >>> p = Parrot("Button1")
> >>> p.on_Button1_mouseClick("event")
>
> You clicked 'Button1'.
>
> --
> Steven.
Thank you. I think that should work perfectly. By using
mouseclick_factory, you've avoided using exec and result in a much
more readable code. The part I really didn't know how is the use of
the new.instancemethod followed by setattr. I'll go try it now.
Thanks again.
More information about the Python-list
mailing list