Top-rated recipes by john mclaughlin http://code.activestate.com/recipes/users/1376161/top/2003-09-19T02:05:17-07:00ActiveState Code RecipesInstall bound methods in an instance (Python)
2003-09-19T02:05:17-07:00john mclaughlinhttp://code.activestate.com/recipes/users/1376161/http://code.activestate.com/recipes/223613-install-bound-methods-in-an-instance/
<p style="color: grey">
Python
recipe 223613
by <a href="/recipes/users/1376161/">john mclaughlin</a>
.
</p>
<p>Python has an extremely flexible object model that allows for assignment of arbitrary objects to arbitrary attributes of instances. I would like to do something like this:
def button( self ): print "Pressed!"
and then assign it to an instance:
mywidget.bigred = button
and call it:
mywidget.bigred()</p>
<p>However this doesn't work because the attribute needs to be a bound method, not a function. Also, the name of the installed function remains button (eg. in stack traces), when we would like it to be bigred.</p>
<p>This recipe provides the installmethod() and renamefunction() functions to solve this problem.</p>