Adding method to a class on the fly

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Jun 23 13:56:51 EDT 2007


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.




More information about the Python-list mailing list