Saturday, December 4, 2010

transform object into different (new-style) class

>>> def transform(obj, cls, *a, **kw):
...    obj.__dict__.clear()
...    obj.__class__ = cls
...    cls.__init__(obj, *a, **kw)
...
>>> class A(object): pass
...
>>> a = A()
>>> type(a)
<class '__main__.A'>
>>> import json
>>> transform(a, json.JSONDecoder)
>>> type(a)
<class 'json.decoder.JSONDecoder'>
>>> a.decode('{"foo":1}')
{u'foo': 1}


Transform an instance of one (new-style) class into another:
1- clear instance dictionary
2- set __class__ to point to new class
3- call new classes __init__() on the cleaned object
Take additional *a, and **kw parameters to pass through arguments to the new class __init__()

No comments:

Post a Comment