Dynamically Mix in Methods into An Instance in Python

As Python is a dynamic language it offers many possibilities how to manipulate object instances during runtime.   We may for instance inject methods from another class,  achieving similar results as  if  this instance has this calls as a mix-in super class. This approach could be useful to hack some existing libraries with extra functionality, in case we have to work with created  instances.

This function will inject methods from mixin_class into instance assuring that method is properly bound to the instance.

We use here python descriptor protocol (__get__)  to get bound method (same thing is actually happening when instance is getting a method from its super class). Alternatively a bound method could be created by this expression (python 2.7):

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">