Ruby has the functionality of being able to add a method to a class at an arbitrary point in your code. I figured Python must have some way for allowing this to happen, and it turned out it did. The method is available instantly to all already existing instances and of course ones yet to be created. If you specify method_name then that name is used for the method call.
One thing to make sure to do is that the function has a variable for the instance to be passed to (i.e. self).
1 2 3 4 5 6 7 8
def funcToMethod(func,clas,method_name=None): """Adds func to class so it is an accessible method; use method_name to specify the name to be used for calling the method. The new method is accessible to any instance immediately.""" func.im_class=clas func.im_func=func func.im_self=None if not method_name: method_name=func.__name__ clas.__dict__[method_name]=func
Why would one use this? I am not completely sure. You could use it as a way to get around having to deal with inheritence. But as I said in the summary, this was mainly to show that it was possible and how flexible Python is.