Just a quick note about Python. I’ve recently tried to find answer for adding methods dynamically to Python objects created at run-time. I’ve seen solutions that use import new and then new.instancemethod, but it seems this module is deprecated and isn’t going to make it in Python 3.0. However the new solution seems fairly simple and elegant (this is what I really like in Python). So basically you use types module and then create a method with types.MethodType. Here’s quick example how you can use it.
>>> import types >>> >>> class Foo(object): ... def __init__(self): ... self.x = 10
Now if you want to add method dynamically at run-time, you create a function out of class context.
>>> def show(cls): ... print cls.x
You should create a first parameter as cls, instead of self, because the bound-method will be using cls attribute as object instance designator. You can use whatever attributes for a function you need, simply remembering that first parameter is always an instance. After you do this, to assign our new function as an object method, we create our object and then assign the function to object as it’s bound-method like this:
>>> bar = Foo() >>> bar.show = types.MethodType(show, bar, Foo)
What types.MethodType does is basically take parameters: “function to bind”, “object instance”, “object class”. It creates a bound method which we must assign to our instance with instance_name.method_name. And voila! We can now use our new method with object created at run-time:
>>> bar.show() 10
That’s it. Really simple and elegant.