How to make type cast for python custom class

Consider a class;

class temp:
    def __init__(self):
        pass

I make an object of it;

obj = temp()

Convert it to string;

strObj = str(obj)

Now, how can i convert strObj to an object of temp class??

org = temp(strObj)

Answer

As noted by Anand in comments, what you’re looking for is object serialization and deserialization. One way to achieve this is through the pickle (or cPickle) module:

>>> import pickle

>>> class Example():
...     def __init__(self, x):
...             self.x = x
...
>>> a = Example('foo')
>>> astr = pickle.dumps(a) # (i__main__nExamplenp0n(dp1nS'x'np2nS'foo'np3nsb.
>>> b = pickle.loads(astr)
>>> b
<__main__.Example instance at 0x101c89ea8>
>>> b.x
'foo'

Note, however, that one gotcha in using the pickle module is dealing with implementation versions. As suggested in the Python docs, if you want an unpickled instance to automatically handle implementation versioning, you may want to add a version instance attribute and add a custom __setstate__ implementation: https://docs.python.org/2/library/pickle.html#object.setstate. Otherwise, the version of the object at serialization time will be exactly what you get at deserialization time, regardless of code changes made to the object itself.

Leave a Reply

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