Adding Methods to a Class at Runtime
Credit: Brett Cannon
Problem
You want to add a method to a class at an arbitrary point in your code for highly dynamic customization.
Solution
The best way to perform this task works for both classic and new-style classes:
def funcToMethod(func, clas, method_name=None):
setattr(clas, method_name or func._ _name_ _, func)If a method of the specified name already exists in the class,
funcToMethod
replaces it with the new implementation.
Discussion
Ruby can add a method to a class at an arbitrary point in your code.
I figured Python must have a way for allowing this to happen, and it
turned out it did. There are several minor possible variations, but
this recipe is very direct and compact, and works for both classic
and new-style classes. The method just added is available instantly
to all existing instances and to those not yet created. If you
specify method_name, that name is used as the
method name; otherwise, the method name is the same as the name of
the function.
You can use this recipe for highly dynamic customization of a running program. On command, you can load a function from a module and install it as a method of a class (even in place of another previous implementation), thus instantly changing the behavior of all existing and new instances of the class.
One thing to make sure of is that the function has a first argument
for the instance that will be passed to it (which is, conventionally,
always named self). Also, this approach works only ...