Monkey patching objects in python

Thursday, May 30, 2013


Every object in Python has a __dict__ member, which stores the object's attributes.
So, you can do something like this:

 class surf(object):  
   def __init__(self, arg1, arg2, **kwargs):  
     #do stuff with arg1 and arg2  
     self.__dict__.update(kwargs)  
 s = surf('arg1', 'arg2', bar=20, baz=10)  
 # Here s is a object of surf with two extra attributes.  



This can be used to add both attributes and functions arbitrarily to objects. 
This can also be used to create a quick struct type. it will be like


 class struct(object):  
   def __init__(**kwargs):  
     self.__dict__.update(kwargs)  
 s = struct(foo=10, bar=11, baz="i'm a string!')  

No comments:

Post a Comment